vee-validate use
* This article is for certain Vue2.0 based friends reference to the use of the actual situation of the project, about the use of the Vue is not superfluous explanation.
First, install
npm install vee-validate@next --save
Note: @next, otherwise version is Vue1.0
bower install vee-validate#2.0.0-beta.13 --save
Second, the reference
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 represents a directory to store your language pack, copied from node_modules vee-validate / dist / locale following / directory to your project
Validator many more applications below revisit.
verify, messages on behalf of custom validation information, strict = true representatives did not set the rules of the form does not verify, errorBagName belong to advanced applications, custom errors after the other config parameters, delay represents the number of ms input, to be studied
Third, based on the 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': 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: Error message inside is usually the name of the form name attribute, unless it is passed in through the Vue instance.
Reminder: develop a good habit, add to each field name
property, if there is no name
property and no binding value, then, validator may not be correct checksum
About errors
:
The code above we see errors.has
, errors.first
, errors are built into the components of a data model to store and process the error message, you can call the following methods:
errors.first('field')
- Get the first error message about the current field ofcollect('field')
- Get all the information about the current field of error (list)has('field')
- Current filed for errors (true / false)all()
- All current form error (list)any()
- the current form for any errors (true / false)add(String field, String msg)
- Add errorclear()
- Clear errorcount()
- the number of errorsremove(String field)
- Clear the filed of all errors
onValidator
Validator is $validator
to be automatically injected into Vue component instance. But also it can be called independent, used to manually check the form for legitimate way to pass an object, which traverse the specified field.
import { Validator } from 'vee-validate'; const validator = new Validator({ email: 'required|email', name: 'required|alpha|min:3', }); // or Validator.create({ ... });
After you set the object parameters can also be constructed in the 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 also pass a value directly to the field, test whether you can by checking, like this:
Validator.validate ( 'In Email', ', [email protected]'); // to true Validator.validate ( 'In Email', 'bar foo @'); // to false // or a plurality of simultaneously checking: validator.validateAll ({ In Email: ', [email protected]' , name: 'John Snow' }); // long as there is a check fails, it returns false
Fourth, the built-in validation rules
after{target}
- a legitimate target date is much larger than the format (DD / MM / YYYY)alpha
- contain only English charactersalpha_dash
- can include English, numbers, underscores, dashesalpha_num
- can contain alphanumericbefore:{target}
- and after the oppositebetween:{min},{max}
- number of between min and maxconfirmed:{target}
- must target the samedate_between:{min,max}
- date between min and maxdate_format:{format}
- legal format to format datesdecimal:{decimals?}
- Digital, and is binary decimalsdigits:{length}
- length of the length of the digitaldimensions:{width},{height}
- Picture in line with the provisions of width and heightemail
- No explanationext:[extensions]
- extensionimage
- Picturesin:[list]
- The value contained in an array of listip
- ipv4 addressmax:{length}
- The maximum length of length charactersmimes:[list]
- file typemin
- max reversemot_in
- in reversenumeric
- allow only numbersregex:{pattern}
- The value must conform to a regular patternrequired
- No explanationsize:{kb}
- The file size does not exceedurl:{domain?}
- (specified domain name) url
Fifth, custom validation rules
1. Direct the definition
Validator = const (value, args) => { // the Return A or A Boolean Promise. } // most basic form, only returns a Boolean value or Promise, with default error
2. Object form
Validator = const { the getMessage (Field, args) { // add to the default error message in English which // Returns A Message. }, the validate (value, args) { // Returns A Boolean or A Promise. } };
3. Add the language-specific error message
Validator = const { messages: { EN: (Field, args) => { // English error }, CN: (Field, args) => { // Chinese error } }, the validate (value, args) { / / Returns A Boolean or A Promise. } };
After you create a rule, extend the method by which added to the Validator
import { Validator } from 'vee-validate'; const isMobile = { messages: { en:(field, args) => field + '必须是11位手机号码', }, validate: (value, args) => { return value.length == 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value) } } Validator.extend('mobile', isMobile);
//或者直接 Validator.extend('mobile', { messages: { en:field => field + '必须是11位手机号码', }, validate: value => { return value.length == 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value) } });
Then you can take directly to the use of mobile as a built-in rules:
<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 rules error messages
Import {the Validator} from 'VEE-the validate' ; const Dictionary = { EN: { messages: { alpha: () => 's Some Dictionary Dictionary English the Message' } }, CN: { messages: { alpha: () => 'to alpha ill-defined rules described in Chinese ' } } }; Validator.updateDictionary (Dictionary);