Search code examples
vue.jsvee-validate

How to create correct rule for validating zero via vee-validate


"vee-validate": "^2.2.11", "vue": "^2.5.16",

I need a simple rule, the rule should be that the input must be required,numeric and greater than 0.

So in this case, if I input 0 it validates correctly(return false), but if I input something like this 0.0 vv returns true. Even if I remove is_not:0, the result still the same.

<sui-input 
  type="text"
  v-validate="'required|decimal|is_not:0'"
  name="cellSize"
  v-model="cellSize">


Solution

  • You could also create a custom rule, like follows.

    created() {
      this.$validator.extend(
      'greaterThanZero',{
       getMessage: field =>  field + ' needs to be > zero.',
       validate: (value) => {
         // value must be > zero
         if (value > 0 ) return true;
         return false;
       }
      });
    },
    

    then call the code on your field instance.

    v-validate="'required|decimal|greaterThanZero'"
    

    more on custom rules here: https://vee-validate.logaretm.com/v2/guide/custom-rules.html#creating-a-custom-rule

    or you could also use this following style (if you were going to add more than one rule for example). Here the code would be inserted in the area where you do your imports, i.e. directly after the script tag.

    import { Validator } from 'vee-validate';
    
    Validator.extend(
      'greaterThanZero',
      (value) => {
        // value must be > zero
        if (value > 0 ) return true;
        return false;
      }
    );
    let instance = new Validator({ greaterThanZeroField: 'greaterThanZero' });
    

    you can now add a second rule to the style directly above using the following code:

     instance.extend('greaterThan1Million', {
     getMessage: field => field +' needs to be > 1,000,000',
     validate: value => (value > 1000000 ? true : false)
     });
     instance.attach({
     name: 'greaterThan1MillionField',
     rules: 'greaterThan1Million'
      });
    

    again that second rule could be called as follows:

    v-validate="'required|decimal|greaterThan1Million'"