VeeValidate Numbers with Decimal Points

November 19, 2019

In your Vue application, you need to validate the numbers with decimal points. For example, price of a product you can use the following method.

I am using VeeValidate module for this

First you have to install the VeeValidate lib for this

You can run the NPM command to install this

npm install vee-validate --save

First you need to import these libs to your Vue single file component

import {
    ValidationProvider,
    ValidationObserver,
    extend
} from 'vee-validate'
import {
    required,
    regex,
    between
} from 'vee-validate/dist/rules';

extend('required', {
    ...required,
    message: '{_field_} is required'
});
extend('regex', {
    ...regex,
    message: 'Numbers Only'
});

You need to add following components also

   components: {
        ValidationProvider,
        ValidationObserver
    },

I am going to validate Product Price filed. This is the normal HTML component

<input class="input is-small" type="text" v-model="product.productprice.purchase_price">

Then I can wrap the ValidationProvider as shown in the following code

 <ValidationProvider :rules="{required: true, regex: /^\d*\.?\d*$/}" vid="purchase_price" name="Prchase Price" v-slot="{ errors }">
      <input class="input is-small" type="text" v-model="product.productprice.purchase_price">
      <span class="error">{{ errors[0]}}</span>
 </ValidationProvider>

You can see I have defined the validation rules as shown in the following line

:rules="{required: true, regex: /^\d*\.?\d*$/}"

It says , Purchase Order is required and number with decimal value