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 fieldname
Attributes, if notname
If the property does not bind the value, the validator may not verify it correctly.
About errors:
We saw the above code,
,
errors
It is a built-in data model of the component, used to store and process error information, and the following methods can be called:
-
('field')
- Get the first error message about the current field -
collect('field')
- Get all error information about the current field (list) -
has('field')
- Is there an error in the current filed (true/false) -
all()
- All errors in the current form (list) -
any()
- Is there any error in the current form (true/false) -
add(String field, String msg)
- Add an error -
clear()
- Clear error -
count()
- Number of errors -
remove(String field)
- Clear all errors in the specified filed
About Validator
Validator is$validator
Automatically 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
- after{target} - A legal date larger than target, format (DD/MM/YYYY)
- alpha - contains only English characters
- alpha_dash - can contain English, numbers, underscores, dash
- alpha_num - can contain English and numbers
- before:{target} - contrary to after
- between:{min},{max} - Number between min and max
- confirmed:{target} - Must be the same as target
- date_between:{min,max} - Date between min and max
- date_format:{format} - Legal format date
- decimal:{decimals?} - Number, and decimals are divided into decimals
- digits:{length} - Number of length
- dimensions:{width},{height} - Pictures that meet the width and height regulations
- email - Not explained
- ext:[extensions] - suffix name
- image - Image
- in:[list] - Value contained in the array list
- ip - ipv4 address
- max:{length} - Characters with maximum length
- mimes:[list] - File Type
- min - max instead
- mot_in - in the opposite
- numeric - Only numbers are allowed
- regex:{pattern} - The value must conform to regular pattern
- required - Not explained
- size:{kb} - File size does not exceed
- url:{domain?} - (specified domain name) url
5. Custom verification rules
1. Direct definition
const validator = (value, args) => { // 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) => { // English error message }, cn: (field, args) => { // 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) => field + 'It must be an 11-digit mobile number', }, validate: (value, args) => { return == 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value) } } ('mobile', isMobile); //or directly ('mobile', { messages: { en:field => field + 'It must be an 11-digit mobile number', }, validate: value => { return == 11 && /^((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: () => 'Some English Message' } }, cn: { messages: { alpha: () => '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.