Vuejs Input form Number Validation example


Input form are fundamental blocks of web page.User enter data, browser display errors on validation failures, submit data to server on submitting the form.

These forms contains different input control types of accepting strings or numbers.

In this post, We are going to learn how to input number validation with accepts only numbers from page in Vuejs Application, It also includes display an error if validation errors exists.

In Vuejs, This can be achieved with multiple ways - using keypress keycode, regular expression and npm libraries like vue-numeric

You can see the full code on Github

Other versions available:

First, Let’s get started creating an application, Write a vuejs component

Create new VueJS application using cli command

First, Please make sure that vue cli is installed or not by check vue –version command in the console.

  B:>vue --version
    @vue/cli 4.5.9

if it gives version number, that means vue is installed, if vue command not found an error in console, please install vue cli using below command.

    npm install -g @vue/cli

It installs vue tool on your machine.

Create Vue applicaiton is an easy using vue command.

    vue create vue-input-example -n
It creates an vue application, folders,dependencies, It install all libraries

Now Application is ready to start running.

First go to root folder, run npm run serve command

    cd vue-input-example
    npm run serve

Application is started and running, can access application https://localhost:8080

limit input numbers only not accept alphabet characters

This example accepts only numeric only and not allow other characters

Let’s create Component for this example.

  • Component name is InputNumber in src/component folder

Input type text is declared and added @keypress event

    <input id="number" @keypress="validateNumber" />

@keypress is an javascript event, called whenever key is pressed. validateNumber is event handler defined in methods section of an component. keycodes for number in keyboard is 48 to 57. that means input box is not allowed other key codes. As keyPressed is directly attached to DOM, any changes refresh the page, event.preventDefault enables not to reload page.

      methods: {
    validateNumber: (event) => {
      let keyCode = event.keyCode;
      if (keyCode < 48 || keyCode > 57) {
        event.preventDefault();
      }
    },
  },

complete code for InputNumber Component:

<template>
  <div>
    <h3>Vuejs Input Number Validation example</h3>
    <input id="number" @keypress="validateNumber" />
  </div>
</template>

<script>
export default {
  name: "InputNumber",
  data() {
    return {};
  },

  methods: {
    validateNumber: event => {
      let keyCode = event.keyCode;
      if (keyCode < 48 || keyCode > 57) {
        event.preventDefault();
      }
    }
  }
};
</script>

<style scoped></style>

As keyCode is not correct way to handle as this will be dependent on key codes of an hardware.

Let’s try using another approach using regular expression

Using regular expression

In the vue methods, replace keycode logic with regular expression

regular expression for number is /[0-9]/

Inside method, get key character and validate against regular expression, if it is not passed, not accept it.

validateNumber: event => {
      const charCode = String.fromCharCode(event.keyCode);
      if (!/[0-9]/.test(charCode)) {
        event.preventDefault();
      }
    }

Input number error on validation

This example do input form validation for numbers only and display errors.

declared an model mynumber in template, to pass from template to/from controller return mynumber and isValid with default values in data function Added @input and @change events to handle input changes. In this event handlers, Check for typed value against regular expression Finally display the errors using v-if directive

<template>
  <div class="hello">
    <h3>Vuejs Input type number validation</h3>
    <br />

    <input type="text" placeholder="Enter Number" v-model="mynumber"  @input="change($event)"
      @change="change($event)"/>
    <div class="error" v-if="!isValid">Number is Invalid</div
  </div>
</template>

<script>
export default {
  name: "InputNumberError",
  data() {
    return {
      mynumber: "",
      isValid: true,
      regex: /[0-9]/
    };
  },
  methods: {
    change:function(e){
      const number = e.target.value
      this.isNumberValid(number);
    },
    isNumberValid: function(inputNumber) {
      this.isValid=   this.regex.test(inputNumber)
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.error{
  color:red;
}
</style>

user can see the output in the browser as follows Vue js Input type number form validation example

conclusion,

This is simple input form validation for type=url, Eventhough we can write custom validation for complexform, however, Node provides different framework veevalidate and joi libraries for simplifying it.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.