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

The compatibility between Javascript and AJAX functions is currently not functioning as expected

I am attempting to send some data to the server using AJAX with the value obtained from a JavaScript variable. Here is the code snippet: <script type="text/javascript> var url; function applyPhoto(_src) { url = _src; var pho ...

I keep encountering an Uncaught TypeError when trying to read the property 'options' of null, despite having the element ID properly defined

I am a newcomer to the world of Javascript and HTML. Despite having the element defined in HTML, I am encountering an exception. Could someone please offer assistance? My goal is to create a shape (initially a circle) based on user input such as shape type ...

What is the process for updating a particular index in a list?

Currently, I am delving into React by working on a task master app. The concept is simple - each user input becomes a new task in an array of tasks. The app features Add, Delete, and Update buttons for managing these tasks. Everything is functioning smoot ...

I am encountering an issue with the useRef function not properly detecting visibility

I'm looking to incorporate a fade-in animation into my React div as I scroll and reach a specific section. Unfortunately, the useEffect function that is supposed to detect the scrolling behavior seems to be malfunctioning and I can't figure out w ...

Discovering the correct element and typing for an HTML attribute through JavaScript

We are currently working on test automation and I am looking for a way to identify the Element and Type associated with it within an html (Data-qa) attribute. For example, when looping through, the Element is identified as input and the type is radio. < ...

What is the best way to incorporate user input and output functionality in a React Javascript application with Material UI for a seamless display?

I am trying to achieve a similar output as shown in this code http://jsfiddle.net/6vqd4vnq/ but using material ui/reactjs. Is there something missing in my setup that is preventing the content from being displayed correctly like in the provided link whic ...

Deselect the checkbox that has been selected using a JavaScript function

I have been searching everywhere for a solution and I am hoping someone in this community can assist me. I am working with a script that triggers when a checkbox is selected from a group of checkboxes. Each checkbox is given a value of "customer id". < ...

Is it possible for pdfjs-dist to be used with Typescript?

Is there a way to preview a PDF as a canvas without importing pdfjs-dist into my project? I have already used the command $yarn add pdfjs-dist to install pdfjs-dist. Do I need to include any additional imports? import pdfjsLib from "pdfjs-dist/build ...

Having trouble with jQuery UI draggable when using jQueryUI version 1.12.1?

Currently, I am diving into the world of jQuery UI. However, I am facing an issue with dragging the boxes that I have created using a combination of HTML and CSS. My setup includes HTML5 and CSS3 alongside jQuery version 1.12.1. Any suggestions or help wou ...

The functionality of the document download button using Express.js and node.js appears to be malfunctioning

For my current project, I am aiming to enable users to effortlessly download a document by simply clicking on a designated button. Project Outline: public/client.js console.log('Client-side code running'); const button = document.get ...

Using Selenium with JavaScript and Python to simulate key presses

Is there a way to simulate key presses as if typing on a keyboard? I am looking to programmatically click on an input element and then emulate the user typing by pressing keys. I prefer not to use XPath selectors combined with sendkeys or similar methods. ...

What are some effective methods to completely restrict cursor movement within a contenteditable div, regardless of any text insertion through JavaScript?

Recently, I encountered the following code snippet: document.getElementById("myDiv").addEventListener("keydown", function (e){ if (e.keyCode == 8) { this.innerHTML += "&#10240;".repeat(4); e.preventDefault(); } //moves cursor } ...

Implementing a delay using setTimeOut function to execute an action upon user input

Take a look at this code snippet: $("#test").on("keyup", (e) => { if(e.target.value.length === 3) { setTimeout(() => { console.log("fired") }, 2000) } }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.m ...

Checking the image loading functionality with Cypress

I am interested in testing Cypress to verify that an image is successfully loaded onto a page. Here is a snippet of my source code: import React from "react"; export default class Product extends React.Component { render() { return ( <div ...

Is there a way to delegate properties in Angular 2+ similar to React?

When working with React, I have found it convenient to pass props down dynamically using the spread operator: function SomeComponent(props) { const {takeOutProp, ...restOfProps} = props; return <div {...restOfProps}/>; } Now, I am curious how I ...

The dropdown in vue-multiselect automatically closes after the first selection is made, ensuring a smooth user experience. However,

I am experiencing an issue where the dropdown closes after the first selection, despite setting close-on-select="false". However, it works properly after the initial select. You can observe this behavior directly on the homepage at the following link: vue ...

How do I see all the implementations of a Vue 3 component when using Volar in VS Code?

Is there a more efficient method for identifying all the instances of a <script setup> component used in various parts of my application? Neither the Go to Implementations nor Go to References options seem to work, so currently I am resorting to man ...

Looking to show the contents of a Rails AJAX JSON response in your application? Having trouble with Javascript displaying [object HTMLDocument] instead? Let

I have been working on a Rails application where I implemented an AJAX / JSON controller to facilitate dynamic HTML updates within the view. For guidance, I referred to this helpful resource: When making a call like this: ../related.json?vendor_id=1&b ...

Guide to forming an array by extracting specific properties from a nested JSON array using javascript

Currently, I have this list: list = { id: 1, arr: [ {index : 1 , description: "lol" , author: "Arthur"}, {index : 2 , description: "sdadsa" , author: "Bob"}, {index : 3 , desc ...

Transform markdown into HTML code

Is there a way to effectively transform a string that resembles the following format: '* [-]Tree Item1', '** [-]Tree Item1-1', '*** Tree Item1-1-1', '*** Tree Item1-1-2', '*** Tree Item1-1-3', '** Tre ...