Vee-validate, Vue2.0 form verification component

Source: Internet
Author: User

Vee-validate, Vue2.0 form verification component

Vee-validate tutorial

This article is suitable for reference by students who have basic knowledge about Vue2.0 and will be used based on the actual situation of the project. I am also using it while learning. If there are any mistakes, please criticize and point out *

I. Installation

npm install vee-validate@next --save

Note: @ next, or Vue1.0

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

Ii. References

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

Component settings:

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

Assets/js/zh_CN indicates the directory where you store the Language Pack. Copy it from the node_modules/vee-validate/dist/locale directory to your project.

Validator has more applications. Let's talk about it later.

Other parameters in config. delay indicates the number of milliseconds entered for verification. messages indicates the custom verification information. strict = true indicates that the form without rules is not verified. errorBagName is an advanced application, custom errors, to be studied

III. Basic usage

<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': errors.has('email') }" name="email" type="text" placeholder="Email">    <span v-show="errors.has('email')" class="help is-danger">{{ errors.first('email') }}</span>  </p></div>

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

Reminder: Make it a good habit to add each fieldnameAttribute. If nonameIf the attribute is not bound to a value, validator may not verify it correctly.

About errors:

The above Code shows thaterrors.has,errors.first,errorsIs a data model built in the component to store and process error messages. You can call the following method:

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

About Validator

Validator is$validatorAutomatically injected by components into the Vue instance. It can also be called independently to manually check whether the form is valid and traverse the specified field by passing in an object.

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

You can also set the object parameters after constructing validator.

import { Validator } from 'vee-validate';const validator = new Validator();validator.attach('email', 'required|email'); // attach field.validator.attach('name', 'required|alpha', 'Full Name'); // attach field with display name for error generation.validator.detach('email'); // you can also detach fields.

Finally, you can directly pass the value to the field to test whether it can pass the verification, as shown in the following code:

Validator. validate ('email ', 'foo @ bar.com'); // truevalidator. validate ('email ', 'foo @ bar'); // false // or check multiple: validator. validateAll ({email: 'foo @ bar.com ', name: 'John snow'}); // if one verification fails, false is returned.

Iv. Built-in validation rules

  1. After {target}-a valid date larger than target, in the format of DD/MM/YYYY)
  2. Alpha-only contains English characters
  3. Alpha_dash-it can contain English letters, numbers, underscores, and dashes.
  4. Alpha_num-can contain English letters and numbers
  5. Before: {target}-opposite 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}-the date is between min and max.
  9. Date_format: {format}-valid format date
  10. Decimal: {decimals ?} -Number in decimals notation
  11. Digits: {length}-number with length
  12. Dimensions: {width}, {height}-images meeting width and height requirements
  13. Email-not explained
  14. Ext: [extensions]-extension name
  15. Image-image
  16. In: [list]-values contained in the array list
  17. Ip-ipv4 address
  18. Max: {length}-characters with the maximum length of length
  19. Mimes: [list]-file type
  20. Opposite to min-max
  21. Opposite to mot_in-in
  22. Numeric-only numbers are allowed
  23. Regex: {pattern}-the value must conform to the Regular pattern
  24. Required-not explained
  25. Size: {kb}-the file size cannot exceed
  26. Url: {domain ?} -(Specified domain name) url

V. Custom validation rules

1. Define directly

Const validator = (value, args) => {// Return a Boolean or a Promise.} // The most basic form. Only the Boolean value or Promise is returned, with the default error prompt

2. Object format

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 messages added to a specified language

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

After the rule is created, use the extend method to add it to Validator.

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

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

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

4. Custom built-in rule error messages

Import {Validator} from 'vee-validate'; const dictionary = {en: {messages: {alpha: () => 'some English message' }}, cn: {messages: {alpha: () => 'Chinese description of the error definition of the alpha rule '}}; Validator. updateDictionary (dictionary );

Now, we have started the translation. If you have time, continue the translation.

For other questions or more advanced applications, see the official documentation Vee-Validate.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.