SoFunction
Updated on 2025-04-04

The input box in Vue only supports four methods of digital input

Method 1: Use @input events and regular expressions

Only numbers are allowed to be entered by listening to the @input event and using regular expressions.

<template>
  <div>
    <input type="text" v-model="inputValue" @input="validateInput" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputValue: ''
    };
  },
  methods: {
    validateInput() {
      // Only numbers are allowed       = (/[^0-9]/g, '');
    }
  }
};
</script>

Method 2: Use @keypress event

Restrict input by listening to the @keypress event, allowing only numbers to be entered.

<template>
  <div>
    <input type="text" @keypress="allowOnlyNumbers" />
  </div>
</template>

<script>
export default {
  methods: {
    allowOnlyNumbers(event) {
      const char = ();
      // Allow input of numbers (0-9)      if (!/[0-9]/.test(char)) {
        (); // Block input      }
    }
  }
};
</script>

Method 3: Use the @keydown event

Use the @keydown event to prevent input of non-numeric characters.

<template>
  <div>
    <input type="text" @keydown="allowOnlyNumbers" />
  </div>
</template>

<script>
export default {
  methods: {
    allowOnlyNumbers(event) {
      // Allowed key codes: 0-9      if ( < '0' ||  > '9') {
        (); // Block input      }
    }
  }
};
</script>

Method 4: Use type="number" and min properties

If you use type="number", you can disable negative input by setting the min attribute, but this still allows the user to enter decimals. To completely prohibit decimals and symbols, verify with the @input event.

<template>
  <div>
    <input type="number" min="0" @input="validateInput" />
  </div>
</template>

<script>
export default {
  methods: {
    validateInput(event) {
      const value = ;
      // Only numbers are allowed      if (!/^\d*$/.test(value)) {
         = (/[^0-9]/g, '');
      }
    }
  }
};
</script>

The above method can effectively prohibit users from entering non-numeric characters in the input box in Vue. Choose the method that suits your needs to implement input limits.

Summarize

This is the article about the only digital input in Vue. For more related Vue input boxes that only support digital input, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me more in the future!