element-ui-verify

If you’ve had enough of ElementUI’s native validation, give it a try!

preface

ElementUI is good, but the form validation experience is not ideal

If product development needs to pay attention to user experience, plug-in development also needs to pay attention to development experience, and good development experience depends on good API design to ensure

I have been dedicated to verification plug-in development for 30 years, and have a family verification plug-in API design (kidding). Vue-verify-pop API is a reference to write before vue-verify-POP API, and to improve, value essence, to its dross, and the essence of the sun and the moon…

This plugin encapsulates ElementUI’s original validator. The core validator is still async-Validator, which is non-intrusive and does not affect your ability to use ElementUI’s native validators

The installation

npm install element-ui-verify
Copy the code

use

The environment

VUE version: 2.x Webpack module environment

A, install

Import Vue from 'Vue' import elementUI from 'elementui-verify' import elementUIVerify from 'elementui-verify' import Vue from 'Vue' import elementUI from 'elementui-verify elementUI Vue.use(elementUI) Vue.use(elementUIVerify)Copy the code

Second, configure validation rules on el-form-item

<template>
  <el-form :model="model">
    <el-form-item prop="age" verify number>
      <el-input v-model.number="model.age"></el-input>
    </el-form-item>
  </el-form>
</template>
<script>
export default{
  data () {
    return {
      model: {
        age: ''
      }
    }
  }
}
</script>
Copy the code

Ok, you have completed a base check that the content cannot be empty and numeric! (Welcome to compare the official version of similar examples)

Default verification rule

  • Length: indicates the length of the verification text
  • MinLength: indicates the minimum length of the verification text
  • Gt: The parity check number must be greater than a certain value
  • Gte: The parity digit must be greater than or equal to a certain number
  • Lt: The check digit must be smaller than a certain number
  • Lte: The parity digit must be smaller than or equal to a certain number
  • MaxDecimalLength: Indicates the maximum number of parity digits
  • Number: indicates whether the check is a number
  • Int: Indicates whether the check is an integer
  • Phone: Check whether it is a mobile phone number (it may need to be updated in the future as the number segment increases)
  • Email: Indicates whether the verification is an email address
  • VerifyCode: indicates whether the verification code is a 6-digit verification code

configuration

errorMessage

Error message template. Default value: Default template

To use a custom template, the template content must overwrite all fields defined in the default template; otherwise, some rules may display empty error messages

fieldChange

The default behavior of the plug-in when a binding field changes. Default: ‘verify’

Note: validation is always triggered when the input box loses focus

verify

The verification is triggered in real time when the bound field changes

clear

If the bound field changes, only the verification result is cleared and the verification is not triggered

Vue.use(elementUIVerify, {
  errorMessageTemplate: yourErrorMessageTemplate,
  fieldChange: 'clear'
})
Copy the code

Description of Important Options

verify

To use this plug-in, the Verify option is required; in other words, you can still use validation native to ElementUI normally if it is not configured

This option can also accept a function value for custom validation methods

errorMessage

For custom checksum fail prompt (null detection and error prompt for custom checksum methods are not affected by this value)

</el-form-item prop="numberProp" verify number error-message=" Please enter the correct number "></el-form-item>Copy the code

canBeEmpty

The plug-in enables non-null validation of input by default. If this option is enabled, all validation after the input is ignored once it is null

This option is generally used in the following situations, such as invitation codes, which can be empty or not empty and need verification

<! --> <el-form-item prop="invitationCode" verify can-be-empty :length="6" Error-message =" the invitation code is incorrect "></el-form-item>Copy the code

space

Whitespace is ignored by default, which means that an input field containing only whitespace will not pass null detection unless this option is set

<el-form-item prop="test" verify space></el-form-item>
Copy the code

alias

Plug-in Retention Macro

Lazy people’s good news, for reuse error prompt, default value: “this input”. Usage Scenarios:

Suppose your null detection error template is:

Empty: '{alias} cannot be empty '}Copy the code

The content of the form is:

<el-form-item prop="unknown" verify></el-form-item alias=" name" prop="name" verify></el-form-item> <el-form-item label=" address" prop="address" verify></el-form-item>Copy the code
  • whenunknownIf the input field is empty, the message “this input cannot be empty” is displayed (the default alias value is “this input”)
  • whenThe nameIf the input field is empty, “Name cannot be empty” will be displayed. (If the alias value is explicitly set, the prompt will replace the template with that value.)
  • whenaddressIf the input field is empty, the message “Address cannot be empty” is displayed. (Most el-form-items require a label item, and the label item represents the input item’s alias.)

fieldChange

See global fieldChange configuration

watch

Listen for other variables to trigger their own validation

A common example: password consistency check, pass1 changes will trigger pass2 check (welcome to compare the official version of similar examples)

<template> <el-form :model="model"> <el-form-item label=" password "prop="pass1" verify> <el-input V-model ="model.pass1"></el-input> </el-form-item> <el-form-item label=" verify password "prop="pass2" :verify="verifyPassword" :watch="model.pass1"> <el-input v-model="model.pass2"></el-input> </el-form-item> </el-form> </template> <script> export  default{ data () { return { model: { pass1: '', pass2: '' } } }, methods: { verifyPassword (rule, val, callback) { if (val ! == this. Pass1) callback(Error) ')) else callback() } } } </script>Copy the code

For another scenario where this option is not appropriate, such as the following example of the minimum maximum number of people, the minimum number of people change to trigger the maximum number of checks:

<template> <el-form :model="model"> <el-form-item label=" minimum number of participants "prop="minNumber" verify int :gt="0"> <el-input V-model. number="model.minNumber"></el-input> </el-form-item> <el-form-item label=" maximum number of participants "prop="maxNumber" verify int :gt="model.minNumber" :watch="minNumber"> <el-input v-model.number="model.maxNumber"></el-input> </el-form-item> </el-form> </template>Copy the code

In fact, the watch option is completely unnecessary here, because the plugin will trigger its own verification in response to changes in all verification parameters. The gt value of the maximum number of participants refers to the model.minNumber, and the verification will be triggered once the Model. minNumber changes

If you watch it again, it will trigger one more time. So this is ok:

<el-form-item label=" maxNumber" prop="maxNumber" verify int :gt="model. MinNumber "></el-form-item>Copy the code

Matters needing attention

  • All option calls must not have uppercase letters, separated by hyphens, as with the vue props property setting rules
  • Length, minLength, gt, gte, lt, lte, maxDecimalLength needs to receive such as numerical option, the value for the digital:length="1")
  • Verify, canBeEmpty, space, number, do not need to receive such as int value options once set up, by assignmentundefinedTo cancel

Rules of abbreviations

Number,int,phone, etc.

<el-form-item prop="prop" verify number></el-form-item> <! <el-form-item prop="prop" verify :number="true"></el-form-item>Copy the code

Gt, gte, lt, lte, maxDecimalLength digital rules do not need to write the number rules

<! -- <el-form-item prop="prop" verify :lte="10"></el-form-item> <! <el-form-item prop="prop" verify number :lte="10"></el-form-item>Copy the code

Global API

addRule (name: string | VerifyRulePropOptions, getter: RuleGetter): RuleGetter

This parameter is used to customize verification rules

name: Rule name

The verification option of this plug-in is based on the Prop of the Vue component, so this parameter can be a configuration item similar to VueProp:

{
  name: 'length',
  type: Number,
  validator (v) {
     return v > 0
  }
}
Copy the code

The advantage of doing this is that you can also put some restrictions on the rule acceptance value itself, avoiding some unnecessary call errors in advance, such as:

</el-form-item prop="prop" verify length=" ha-ha "></el-form-item>Copy the code

In this case, it is very likely that your validation text length rule will be abnormal. Of course, if you believe in the caller or the rule that no value is received, you can simply do this:

import elementUIVerify from 'element-ui-verify'
elementUIVerify.addRule('length', length => SomeRule)
Copy the code

getter: asyncValidatorRule Obtaining method

This callback can return a single rule or an array of rules. For details about rules, see Async-Validator

/ / a single () = > ({type: "number", the message: 'please enter the Numbers'}) / / multiple gte = > [{type: "number", the message:' please enter the Numbers'}, {type: 'number', min: gte, message: 'The number cannot be less than ${gte}'}]Copy the code

If you have any questions about the repeated definition of type for multiple rules in the above example, look here

getRule (name: string): RuleGetter

Used to obtain verification rules. It is used with custom verification rules to reuse existing rules

The return is the getter parameter passed in by addRule

getErrorMessage (name: string, templateData? : any): string

Use to get error messages from the common error message template. This parameter is used together with custom verification rules

Assume the error message template is

{// no Macro empty: 'This input cannot be empty ', // Macro equals RuleName length exactly: // Macro does not equal RuleName maxDecimalLength: 'This input accepts at most {MDL} decimal digits'}Copy the code

Call example:

The import elementUIVerify from 'element - the UI - verify / / return: "the input item content can't be empty" elementUIVerify. GetErrorMessage (' empty') / / return: "Length of the input item need equal to 10" elementUIVerify. GetErrorMessage (' length, 10) / / return: "The input item accepted at most 2 decimal places" elementUIVerify. GetErrorMessage (' maxDecimalLength '{2} MDL:)Copy the code

Customize the verification method

If the built-in verification rules cannot meet your requirements, you can insert your own verification methods into the verification rules

A user-defined verification method is executed only after all verification rules pass

<template> <el-form :model="model"> <el-form-item label=" cardNumber" prop="cardNumber" :verify="verifyCardNumber" :length="6"> <el-input v-model.number="model.cardNumber"></el-input> </el-form-item> </el-form> </template> <script> export default{ data () { return { model: { cardNumber: '' } } }, methods: VerifyCardNumber (rule, val, callback) {// check whether the card number starts with 010 or 011. // val: validator // callback: async-validator If (['010', '011'].indexof (val.substr(0, 3)) = = = 1) callback (Error (' the wrong card number)) else callback ()}}} < / script >Copy the code

User-defined verification rules

The difference between this method and the custom verification method is that this method applies globally, which is equivalent to adding the plug-in’s own verification rules

As mentioned in the introduction, the core validator of this plug-in comes from Async-Validator, so you need to consult its documentation for validation rules

Example 1: Add a rule that verifies whether it is a 10-bit integer

Import elementUIVerify from 'element-ui-verify' const intRuleGetter = import elementUIVerify from 'elementui-verify' const intRuleGetter = import elementUIVerify from 'elementui-verify' const intRuleGetter = import elementUIVerify from 'elementui-verify Elementuiverify.getrule ('int') elementuiVerify.addRule ('int10', () => [// first check if intRuleGetter() is an integer, Validator (rule, val, callback) {if ((val + ").length!== 10) {// Try to define the error message in the error template (suppose {int10: 'this input item for 10 integer}) const errorMessage = elementUIVerify. GetErrorMessage (' int10) callback (Error (errorMessage)} the else callback() } } ])Copy the code

This completes a simple rule extension so that you can invoke your custom rules as if they were the default rules from anywhere, as follows:

<el-form-item prop="prop" verify int10></el-form-item>
Copy the code

Example 2: Add a rule that verifies whether it is an arbitrary bit integer. The difference is that this rule accepts a rule parameter

import elementUIVerify from 'element-ui-verify' const intRuleGetter = elementUIVerify.getRule('int') // Elementuiverify.addrule ({name: 'intLength', type:) {elementUIVerify.addRule({name: 'intLength', type: Number}, intLength => [intRuleGetter(), // Validator (rule, val, Callback) {if ((val + ").length!== intLength) { 'the input item for {intLength} integer'} const errorMessage = elementUIVerify. GetErrorMessage (' intLength ', intLength) callback(Error(errorMessage)) } else callback() } } ])Copy the code

Call:

<el-form-item prop="prop" verify :int-length="10"></el-form-item>
Copy the code

For more examples, you can look directly at the addition of default rules in the plugin source code

The default validation of plug-ins does not pass the prompt template

{empty: 'Please add this content ', length:' Please enter at least {length} bits ', minLength: 'Please enter at least {minLength} bits ', number:' Please enter a number ', int: 'Please enter an integer ', lt: 'Input number should be less than {lt}', LTE:' Input number should not be greater than {lte}', gt: 'Input number should be greater than {gt}', gte:' Input number should not be less than {gte}', maxDecimalLength: 'This entry will accept {maxDecimalLength} decimal digits at most ', phone:' enter the correct mobile phone number ', email: 'Enter the correct email address ', verifyCode:' Enter the correct verification code '}Copy the code

Q&A

Why not kill the prop configuration item? I hate having to write the checksum rule every time!

I am tired. However, this plug-in is based on ElementUI, so many places are limited by the original validation mechanism and try not to affect it as much as possible. For example, the prop option, if disabled, will affect the validation of the El-Form, because ElementUI stores the validation queue as a PROP UID

How do I switch the verification type? For example, an input field might include a mobile phone number or an email address

<el-form-item prop="prop" verify phone v-if="isPhone"></el-form-item>
<el-form-item prop="prop" verify email v-else></el-form-item>
Copy the code

This can also be done if the rules don’t change much (checking is triggered immediately when switching types this way)

<el-form-item prop="prop" verify :phone="isPhone ? true : undefined" :email="isPhone ? undefined : true"></el-form-item>
Copy the code

other

When writing the gTE rule, I first refer to the async-Validator number type rule and then refer to its Range rule. The Range rule supports both strings and numbers, so we need to explicitly set type for numbers: Number, which may cause the GTE rule to check for numbers twice, but has little performance impact

[{type: 'number'}, {min: 3}] // However, you must write [{type: 'number'}, {type: 'number', min: }] // Of course, you can also write a custom check function to avoid this problem, but this problem is not necessary [{type: 'number'}, {validator (rule, val, callback) {if (val < 3) callback(Error(' not less than 3'))}}]Copy the code

It is not a disadvantage of Async-Validator. Based on the current rule convention of Async-Validator, rule inference will not benefit much, and it will increase the uncertainty of verification rules and cause confusion to the caller. However, for this purpose only, consider separating the range rules for text and numbers

So here you might ask why don’t you just use a single rule?

{type: 'number', min: 3, errorMessage: 'xxxx'}
Copy the code

If so, the input non-numeric error message will be in the original error message template. In order not to break ElementUI’s native validations (modifying the original error prompt template) and to maximize reuse of the async-Validator’s built-in validations, we have to split the rules to make the validation error prompt more specific

Later, when you customize the verification rules, you can also consider rule splitting to make the error message more specific if similar problems occur

The latter

Since the validation option of this plug-in is based on VueProp, it has the following disadvantages:

  • As ElementUI is updated, there may be future conflicts with some of its new options
  • It is difficult to execute verification in the order of verification rules. The current order is null check > General Rule > Custom verification method. However, the impact of this rule is not very large, and most scenarios under existing rules do not need to consider rule order