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 fieldname
Attribute. If noname
If the attribute is not bound to a value, validator may not verify it correctly.
About errors:
The above Code shows thaterrors.has
,errors.first
,errors
Is a data model built in the component to store and process error messages. You can call the following method:
errors.first('field')
-Obtain the first error message about the current field.
collect('field')
-Get all error information about the current field (list)
has('field')
-Current filed error (true/false)
all()
-All errors in the current form (list)
any()
-Whether the current form has any errors (true/false)
add(String field, String msg)
-Add error
clear()
-Clear Error
count()
-Error count
remove(String field)
-Clear all errors of the specified filed.
About Validator
Validator is$validator
Automatically 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
- After {target}-a valid date larger than target, in the format of DD/MM/YYYY)
- Alpha-only contains English characters
- Alpha_dash-it can contain English letters, numbers, underscores, and dashes.
- Alpha_num-can contain English letters and numbers
- Before: {target}-opposite to after
- Between: {min}, {max}-number between min and max
- Confirmed: {target}-must be the same as target
- Date_between: {min, max}-the date is between min and max.
- Date_format: {format}-valid format date
- Decimal: {decimals ?} -Number in decimals notation
- Digits: {length}-number with length
- Dimensions: {width}, {height}-images meeting width and height requirements
- Email-not explained
- Ext: [extensions]-extension name
- Image-image
- In: [list]-values contained in the array list
- Ip-ipv4 address
- Max: {length}-characters with the maximum length of length
- Mimes: [list]-file type
- Opposite to min-max
- Opposite to mot_in-in
- Numeric-only numbers are allowed
- Regex: {pattern}-the value must conform to the Regular pattern
- Required-not explained
- Size: {kb}-the file size cannot exceed
- 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.