How can I create a textbox in vue.js that only allows numeric input?

methods: {
    acceptNumber() {
      var x = this.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
      this.value = !x[2] ? x[1] : '(' + x[1] + ')' + x[2] + (x[3] ? '-' + x[3] : '');
    }
<input class="input-section label-set"
       type="text"
       v-model.trim="$v.mobile.$model"
       :class="{'is-invalid': validationStatus($v.mobile)}"
       placeholder="Enter your mobile number"
       :maxlength="maxmobile" v-model="value"
       @input="acceptNumber"
/>

<div v-if="!$v.mobile.minLength"
     class="invalid-feedback"
>Kindly check phone {{ $v.mobile.$params.maxLength.min }} number.</div>

To modify the code in the input field below to only accept numbers and change the number pattern to display as "4356754356" without any special characters or spaces.

Answer №1

To ensure only numbers are inputted, include the following code within the tag:

onkeypress='return event.charCode >= 48 && event.charCode <= 57'
. I have tested it and it works effectively.

<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>

Answer №2

Is there a way to create a textbox [input] that only accepts numbers for the code? Specifically, a phone number input that does not allow characters.

To ensure only numeric characters are accepted, we need to make adjustments to the acceptNumber() method's complex string manipulation process.

A helpful approach when dealing with complicated string manipulations is to break down the process into manageable sections.

The following code snippet demonstrates this concept:

var x =this.value.replace(/\D/g,'').match(/(\d{0,3})(\d{0,3})(\d{0,4})/;
this.value=!x[2]?x[1]:'('+x[1]+')'+x[2]+(x[3]?'-'+x[3]:'');

This can be simplified into step-by-step instructions:

let thisValue = '(123) 456-7890';

let x = thisValue.replace(/\D/g,'');
console.log(`x: "${x}"`);

x = x.match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
console.log('x.match:', JSON.stringify(x));

thisValue = !x[2]
  ? x[1]
  :'(' + x[1] + ')' + x[2] +
    (x[3] ? '-' + x[3] : '');
console.log(`thisValue: "${thisValue}"`);

By utilizing the first item of the x array, which contains just the digits, we can fulfill the request from the user:

this.value = x[0];  // "1234567890"

Below is a refined version of the original code incorporating the above modification. It effectively filters out any non-numeric characters as they are entered.

const app = new Vue({
  el: '#app',
  data: {
    value: '',
    maxmobile: 10
  },
  methods: {
    acceptNumber() {
      const x = this.value.replace(/\D/g, '');
      console.log('this.value:', this.value, 'x:', x);
      this.value = x;
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<div id="app">
  <form>
    <input placeholder="Enter your mobile number" :maxlength="maxmobile" v-model="value" @input="acceptNumber" />
    <button type="submit">Submit</button>
  </form>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In Angular, when a component is clicked, it is selecting entire arrays instead of just a single item at a

I am currently working on implementing a rating feature using Angular. This component will be used to rate different languages based on how proficient I am with them. My issue lies in the fact that when I click on one array element, it automatically selec ...

Animating a dotted border path in SVG for a progress bar effect

I am attempting to create an animation for a dotted SVG circle that resembles a progress bar, where it fills itself over a duration of 3 seconds. However, I am facing difficulties in achieving this effect with the dotted border. The current code I have doe ...

How can a callback be properly passed in programming?

My coding approach is outlined below: var CustomLibrary = (function (window, $, undefined) { return { URI: 'http://testpage/API/', OnSuccess: function (data, status) { }, OnError: function (request, status, error) { } ...

Executing a function on the window object in JavaScript

I have come across the following code and am seeking guidance on how to get the last line to function correctly. The API I am using currently employs _view appended as its namespacing convention, but I would prefer to switch to something like arc.view.$f ...

What is the best way to organize an Express application that handles both API requests and views?

Currently, I am in the process of developing a small application that will function as both a website and its API. To achieve this, I am utilizing Node, Express, and Webpack. The structure of my directory is organized as follows: >client |>dist ...

What is the best method for obtaining the HTML content of a webpage from a different domain?

I'm in the process of creating a website where I have the requirement to retrieve the HTML content of a different site that is cross-domain. Upon researching, I came across YQL. However, I don't have much experience with YQl. Is it possible to ad ...

Obtain the data stored in an object within an array

I am attempting to retrieve the values of objects within an array. const bugSchema = new Schema({ title: { type: String, required: true }, comments:[ { user:{ type: String, required: true }, c ...

Having trouble getting webpack and babel to start using npm

Greetings, wonderful people of the internet! I am a newcomer to the enchanting world of programming and I am facing a perplexing issue. Although Webpack is trying to guide me towards the solution, I seem to be struggling with fixing it on my own. const pa ...

Conceal the scroll bar while the page preloader is active

Is there a way to hide the scroll bar while the preloader is loading on a webpage? I want to prevent users from scrolling until the preloader disappears. I have tried using CSS and setting the body overflow to hidden, but it's not working as expected. ...

Warning in Google Script editor

Currently, I am working on creating some quick scripts to manipulate spreadsheets in my Google Drive. However, I am cautious about the script unintentionally running and making changes to data before I am ready or executing multiple times after completing ...

Using jQuery Ajax to send data and retrieve responses in the Codeigniter framework

I am struggling with passing values in CodeIgniter and I need some guidance. Could you provide an example code snippet using CodeIgniter to send a value from a view to a controller using Ajax and jQuery, and then display the result on the same page? In my ...

Sharing application state between different routes in React Router v4 can be achieved by using methods such

I'm seeking solutions to address the following challenge: Without utilizing any state management library, I solely rely on React. The primary application state is contained within the <MyFoodApp/> component, which includes an array of restaura ...

Function for testing global variable stub in JavaScript

Currently, I am in the process of writing Unit tests for a React application. Within the page header, the tracking library 'mixpanel' is inserted between <script> tags as outlined in their documentation: . The documentation states that "Th ...

I do not prefer output as my optimal choice

My preference is to create drill down buttons rather than focusing on output. Currently, the output appears as: https://i.sstatic.net/8qs5F.png The content of index.html is as follows: <html>  <head> <script type="text/javascript" ...

Implementing dynamic controls in an ASP.NET MVC5 application using AngularJS

I am currently working on a project that will utilize MVC5, angularJS, and bootstrap for development. One of the key features in my project is a dropdown menu called "expense type". Upon selecting a value from this dropdown, additional controls need to be ...

React: Modifying a single input field out of many

Can someone please review this code snippet: https://stackblitz.com/edit/react-koqfzp?file=src/Section.js Whenever I add an item, a random number is also added that I want to be able to edit. This number is displayed in a Material UI Text Field component. ...

Solution for Organizing Tables

I've sourced data from various JSON API links and displayed it in a table. Currently, my code looks like this: <script src="js/1.js"></script> <script src="js/2.js"></script> Above this code is the table structure with <t ...

React testing with Mocha experiencing an Invariant violation

Currently, I am in the process of setting up a React project using Electron. Lately, I have been experimenting with configuring Mocha as my test framework. Everything seems to be working fine when I run: "test": "mocha -w --require babel-core/register ...

Use the `fetch` method in JavaScript/TypeScript to make an API call to an IPFS URI but be prepared for potential issues like CORS restrictions, network errors, or

I am currently working on a Next.js project with TypeScript in the browser, and I need to execute the following fetch request: const tokenURIResponse = await fetch( "ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg ...

Keep the first column of an HTML table fixed as you scroll horizontally

Below is an HTML table that I have created: <table id="customers" class="table table-bordered" width="100%"> <thead> <tr> <th colspan="2">Activities</th> <th>Mon 17</th> <th>Tue 18</th> </thead> ...