SoFunction
Updated on 2025-03-09

Detailed explanation of the use of vue2.0 form verification component vee-validate

vee-validate usage tutorial

This article is suitable for students with a certain foundation in Vue 2.0 and is used according to the actual situation of the project. There is no unnecessary explanation for the use of Vue. I also use it while learning. If there are any mistakes, please criticize and point out*

1. Installation

npm install vee-validate@next --save

Note: @next, otherwise it will be Vue 1.0 version

bower install vee-validate#2.0.0-beta.13 --save

2. Quote

import Vue from 'vue';
import VeeValidate from 'vee-validate';
(VeeValidate);

Component settings:

import VeeValidate, { Validator } from 'vee-validate';
import messages from 'assets/js/zh_CN';
({
  zh_CN: {
    messages
  }
});
const config = {
  errorBagName: 'errors', // change if property conflicts.
  delay: 0,
  locale: 'zh_CN',
  messages: null,
  strict: true
};
(VeeValidate,config);

assets/js/zh_CN represents the directory where you store the language package, copy it to your project from the node_modules/vee-validate/dist/locale directory.

There are more applications for Validator, which will be discussed below.

config other parameters, delay means how many ms are entered to verify, messages represent custom verification information, strict=true means that forms without rules are not checked, errorBagName is an advanced application, custom errors, to be studied

3. Basic use

<div class="column is-12">
  <label class="label" for="email">Email</label>
  <p class="control">
    <input v-validate data-rules="required|email" :class="{'input': true, 'is-danger': ('email') }" name="email" type="text" placeholder="Email">
    <span v-show="('email')" class="help is-danger">{{ ('email') }}</span>
  </p>
</div>

Reminder: The name in the error message is usually the name attribute of the form, unless it is passed in through a Vue instance.

Reminder: Develop good habits and add them to each fieldnameAttributes, if notnameIf the property does not bind the value, the validator may not verify it correctly.

About errors:

We saw the above code,,errorsIt is a built-in data model of the component, used to store and process error information, and the following methods can be called:

  1. ('field')- Get the first error message about the current field
  2. collect('field')- Get all error information about the current field (list)
  3. has('field')- Is there an error in the current filed (true/false)
  4. all() - All errors in the current form (list)
  5. any() - Is there any error in the current form (true/false)
  6. add(String field, String msg) - Add an error
  7. clear() - Clear error
  8. count() - Number of errors
  9. remove(String field)- Clear all errors in the specified filed

About Validator

Validator is$validatorAutomatically injected into the Vue instance by the component. At the same time, it can also be called independently to manually check whether the form is legal and to traverse the specified field in it by passing in an object.

import { Validator } from 'vee-validate';
const validator = new Validator({
  email: 'required|email',
  name: 'required|alpha|min:3',
}); 
// or ({ ... });

You can also set object parameters after constructing validator

import { Validator } from 'vee-validate';
const validator = new Validator();

('email', 'required|email'); // attach field.
('name', 'required|alpha', 'Full Name'); // attach field with display name for error generation.

('email'); // you can also detach fields.

Finally, you can also pass the value directly to the field to test whether it can pass the verification, like this:

('email', 'foo@'); // true
('email', 'foo@bar'); // false
//Or check multiple at the same time:({
  email: 'foo@',
  name: 'John Snow'
});
//As long as one check fails,Just returnfalse

4. Built-in verification rules

  1. after{target} - A legal date larger than target, format (DD/MM/YYYY)
  2. alpha - contains only English characters
  3. alpha_dash - can contain English, numbers, underscores, dash
  4. alpha_num - can contain English and numbers
  5. before:{target} - contrary to after
  6. between:{min},{max} - Number between min and max
  7. confirmed:{target} - Must be the same as target
  8. date_between:{min,max} - Date between min and max
  9. date_format:{format} - Legal format date
  10. decimal:{decimals?} - Number, and decimals are divided into decimals
  11. digits:{length} - Number of length
  12. dimensions:{width},{height} - Pictures that meet the width and height regulations
  13. email - Not explained
  14. ext:[extensions] - suffix name
  15. image - Image
  16. in:[list] - Value contained in the array list
  17. ip - ipv4 address
  18. max:{length} - Characters with maximum length
  19. mimes:[list] - File Type
  20. min - max instead
  21. mot_in - in the opposite
  22. numeric - Only numbers are allowed
  23. regex:{pattern} - The value must conform to regular pattern
  24. required - Not explained
  25. size:{kb} - File size does not exceed
  26. url:{domain?} - (specified domain name) url

5. Custom verification rules

1. Direct definition

const validator = (value, args) =&gt; {
  // Return a Boolean or a Promise.
}
//The most basic form,Return only the boolean value orPromise,With default error prompt

2. Object Form

const validator = {
  getMessage(field, args) { // Add to the default English error message    // Returns a message.
  },
  validate(value, args) {
    // Returns a Boolean or a Promise.
  }
};

3. Error message added to the specified language

const validator = {
  messages: {
    en: (field, args) =&gt; {
      // English error message    },
    cn: (field, args) =&gt; {
      // Chinese error message    }
  },
  validate(value, args) {
    // Returns a Boolean or a Promise.
  }
};

After creating the rules, add them to Validator using the extend method

import { Validator } from 'vee-validate';
const isMobile = {
  messages: {
    en:(field, args) =&gt; field + 'It must be an 11-digit mobile number',
  },
  validate: (value, args) =&gt; {
    return  == 11 &amp;&amp; /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value)
  }
}
('mobile', isMobile);

//or directly
('mobile', {
  messages: {
   en:field =&gt; field + 'It must be an 11-digit mobile number',
  },
  validate: value =&gt; {
   return  == 11 &amp;&amp; /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value)
  }
});

Then you can use mobile as a built-in rule:

<input v-validate data-rules="required|mobile" :class="{'input': true, 'is-danger': ('mobile') }" name="mobile" type="text" placeholder="Mobile">
<span v-show="('mobile')" class="help is-danger">{{ ('mobile') }}</span>

4. Customize the error message of built-in rules

import { Validator } from 'vee-validate';

const dictionary = {
  en: {
    messages: {
      alpha: () =&gt; 'Some English Message'
    }
  },
  cn: {
    messages: {
      alpha: () =&gt; 'Incorrect definition of alpha rules Chinese description'
    }
  }
};

(dictionary);

That’s all for now. I should have started it. I will continue to translate when I have time.

For other issues or more advanced applications, please refer to the official documentationVee-Validate

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.