Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement the Vue Element-ui form Verification rules

2025-03-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today Xiaobian to share with you how to achieve the Vue Element-ui form verification rules of the relevant knowledge, detailed content, clear logic, I believe that most people are too aware of this knowledge, so share this article for your reference, I hope you have something to gain after reading this article, let's take a look at it.

1. Preface

   Element-ui form validation rules, so that the error prompt can be displayed directly under the form-item without popup box, so it is still very useful.

   after I checked the form on the login page, I thought I already knew the verification rules of the form. But when I used the form validation rules in depth, I encountered the following problems:

How to determine whether the attribute value is in a certain range, and this range can be specified arbitrarily?

How to determine whether the attribute value is a certain value?

Multiple attributes joint verification, the current attribute verification rules depend on the value of another attribute, how to verify? For example, on the registration page, ID types include email address, mobile phone number and ID card number. If you choose different types, the verification rules for IDValue attributes are different. How to deal with them?

Two modes, enter the same form component, some fields can not use validation rules, that is, the objects of rules will be different. How to deal with this situation?

2. The entry mode of rule verification

2.1, sample code

   is used as an introduction to rule verification. Take the login page as an example, the code is as follows:

XX management system login

点击更换

Log in to import {mapMutations} from "vuex" export default {data () {return {form: {username: ", password:", verifyCode: ",}, rules: {username: [{required: true, message:" user name cannot be empty ", trigger:" blur "},] Password: [{required: true, message: "password cannot be empty", trigger: "blur"}, {min: 6, max: 30, message: "password 6-30 digits", trigger: "blur"}], verifyCode: [{required: true, message: "passcode cannot be empty", trigger: "blur"},]}} }, methods: {/ / submit login submitForm (formName) {let _ this = this; / / perform verification this.$ refs [formName] .validate (valid = > {/ / pass true, one failure is false if (valid) {/ / pass verification / / login processing / /.... } else {/ / failed verification console.log ("verification failed"); return false;}});},}} 2.2, form entry

   form entry, indicating the use of verification rules:

  : rules= "rules" indicates that verification rules use rules rule objects, and you can also use other names, such as rules1.

2.3.The prop item

The    prop entry, which indicates which fields may use validation rules:

   if the property value specified by the prop entry, such as username, also has a corresponding entry in rules, the property value performs a rule check. This property must be a property of the data object bound by the model property of form, in this case form, which is defined in data:

Form: {username: ", password:", verifyCode: ",}, 2.4, rules entries

The    rules entry, the check rule set, is defined in data and its name must be the same as the name of the rules rule object bound to the: rules attribute of form.

Rules: {username: [{required: true, message: "user name cannot be empty", trigger: "blur"},], password: [{required: true, message: "password cannot be empty", trigger: "blur"}, {min: 6, max: 30, message: "password 6-30 digits", trigger: "blur"}] VerifyCode: [{required: true, message: "CAPTCHA cannot be empty", trigger: "blur"},]}

   this is an object. The type of each element is: {attribute name: [rule]}, and the attribute name is relative to the attribute value of prop. [rule] is an array of rules, and each item in the array of rules is a check rule for this property.

2.5, rule item

The    rule entry, which is the element of a regular array, is the focus of this article. Let's first parse the element items of the above rules:

Required: indicates whether there must be a value. The value is true/false. If it is true, it means there must be a value. If there is no value, the check fails; if it is false, no value is allowed, but if there is a value, it does not affect the use of other rules.

Message: prompt message, which is prompted when the check fails.

Trigger: trigger method. A value of blur/change,blue indicates loss of focus, which is generally used in input components. Change is a value change and is generally used in the selection box.

Min: minimum length of a string.

Max: maximum length of the string.

With these explanations in   , it is not difficult to understand the verification rules for the attributes defined by rules above.

2.6. Rules of use

This.$refs ['form "] .validate (valid = > {/ / validate passed as true, one failure is false if (valid) {/ / passed verification} else {/ / failed verification})

  , the validate method, requires all verification rules to be passed before it is released. Where $refs ['form "] points to the value of the ref attribute of form.

2.7, the core of rule verification

The core of    rule verification is the async-validator plug-in, official website: https://github.com/yiminghe/async-validator.

The plug-in is used by    Element-UI and encapsulated. Official website: https://element.eleme.cn/#/zh-CN/component/form.

  , therefore, the information on both sides will be helpful.

3. The advanced mode of rule verification

3.1. Nested object property name

   sometimes, prop is not a simple property, but a property wrapped under other objects. Such as:

A model-bound form object of    form in the form of:

Form: {/ / form data field to facilitate the submission of the backend It is recommended to be consistent with UserInfo field naming formData: {userId: 0, loginName: ", passwd:", / /...}, / / the user type selection box currently displays the value userTypeLabel: ", / /.}

   at this time, the element definition of rules cannot be in the following form:

FormData.loginName: [{required: true, message: "login cannot be empty", trigger: "blur"},]

   like this, the compilation will report errors!

   should be in the following form:

"formData.loginName": [{required: true, message: "login cannot be empty", trigger: "blur"},]

   wraps it in single or double quotes and turns it into a string.

3.2.Custom verifier validator

   about the custom validator validator, there are many related materials on the Internet, such as validator, which is commonly used for regular checking.

   rule definition method:

"formData.loginName": [{required: true, message: "login cannot be empty", trigger: "blur"}, {validator:loginNameValidator, trigger: "blur"}]

   indicates that the "formData.loginName" attribute uses loginNameValidator's validator. Considering the reuse of code, the custom validator is generally turned into a js file, which is convenient for other pages or projects to use.

   create the validator.js file under the / src/common/ directory, as follows:

/ * Login name check * / export function loginNameValidator (rule, value, callback) {const reg= / ^ [a-zA-Z] [wmer. @] * $/; if (value = = "" | value = = undefined | | value = = null) {callback ();} else {if (! reg.test (value)) {callback ("required: start with the English letter, followed by alphanumeric and _ -. @ symbol");} else {callback ();}

   imports this validator.js file in the vue file:

Import {loginNameValidator} from "@ / common/validator.js"

   if you need to import more than one external validator, include multiple in {}, such as {loginNameValidator,passwordValidator}.

  , there's a little hole here, just to mention it.

   according to the directory structure, I first use the following statement:

Import {loginNameValidator} from ".. / common/validator.js"

   result, compilation error, said that the ".. / common/validator.js" file could not be found, so various path representation methods attempted, all failed. In the end, it passed with @ instead, because alias is configured in / bulid/webpack.base.conf.js, indicating that @ represents the src directory.

   returns to the custom validator in the form of:

Function ValidatorFuncName (rule, value, callback)

The name of the    method, as you wish.

In fact, the full form of    is:

Function ValidatorFuncName (rule, value, callback, source, options)

The meaning of    parameter is as follows:

Rule: point to the object of the rule. You can add the first sentence to the method code:

Console.log (rule)

The rule parameter can be printed out to see that it is the object data of this rule.

Value: the value of the property, which is the value to be verified.

Callback: points to the callback function at the end of the check. If the check is passed, callback () is called. If it fails, the following form is used:

Callback (new Error ("specific hints"))

   or prompt with parameters:

Return callback (new Error (`${rule.field} must be lowercase alphanumeric rooms`))

   note that string formatting is not enclosed in single quotation marks, but in "~" symbols.

   can also use the official website of async-validator (https://github.com/yiminghe/async-validator)):

Util.format ("% s must be lowercase alphanumeric characters", rule.field)

The    util file contains the format method, this util.ts file, in the src/ directory of the official website, this is a ts file, which can be similar to a public method.

   can actually return an array of Error, errors, such as:

Const errors = []; errors.push ("required to begin with the English letter, followed by alphanumeric and _ -. @ symbols"); errors.push (new Error ("3444 requirements: English"); return callback (errors)

   but from the actual effect, the form only shows the first line of prompts, it is estimated that the Element form does not support the display of multi-line error messages.

Source: for the property object that calls the check, you can print it out and have a look.

Options, additional parameters, mainly predefined message formats, can also be printed out to have a look.

   's more complex validators can carry parameters, such as:

/ / Integer range value check export const intRangeValidator = (min, max) = > (rule, value, callback) = > {var isInRange = (value > = min) & & (value {const reg= / ^ [a-zA-Z] [wmer]. @] * $/; if (value = = "" | value = = undefined | | value = = null) {callback ();} else {if (! reg.test (value)) {callback ("required: start with the English letter, followed by alphanumeric and _ -. @ symbol");} else {callback ();}

   may be defined directly in the rule:

"formData.loginName": [{required: true, message: "login cannot be empty", trigger: "blur"}, {validator (rule, value, callback) {const reg= / ^ [a-zA-Z] [wmer. @] * $/; if (value = = "" | | value = = undefined | | value = = null) {callback ();} else {if (! reg.test (value)) {callback (new Error ("required: start with the English letter, followed by alphanumeric and _ -." @ symbol ");} else {callback ();}, trigger:" blur "}], 3.3.Type type

The basic usage of the    type type is as follows:

"formData.age": [{type: "integer", message: "value required to be an integer", trigger: "blur"},]

The    type is also a rule entry, and if it does not meet the type requirements, it prompts an error message.

The types supported by    rules are as follows:

String, string type, which is the default type. If you do not specify type, the default is string.

Number, numeric type. Including integers and decimals.

Integer, integer type.

Float, floating point type, cannot be an integer at this time, it must have a decimal point.

Boolean, Boolean type, true/ false value.

Array, array type.

Object, object type, cannot be an array.

Enum, enumerate the type, and then need to declare the enumerated type.

Method, function (or method) type.

Regexp, a regular type, must be a legal regular expression that can be created through new RegExp.

Date, date type, the value must be converted to a valid date value.

Url,url type, the value needs to conform to the url format.

Email,email type, which conforms to the mailbox format.

The form of the hex,16 binary representation. Such as 0xFF12.

Any, any type, unlimited.

   the url and email types here can be directly used for attribute verification of related meanings, such as:

"formData.email": [{type: "email", message: "must conform to email address format", trigger: "blur"}]

   date types are also useful, and these built-in types allow us to deal with them without having to use a custom validator validator.

   for numeric types (number,integer,float) and Boolean types, because the input of input is a string, type conversion must be performed, otherwise the check will fail. The use of transform is involved here.

3.3.The data conversion transform

   transform is a hook function that processes and validates data before starting validation. Such as the following example:

"formData.age": [{type: "integer", message: "value required to be an integer", trigger: "blur", transform (value) {return parseInt (value);},},]

After    is converted by the transform type, the verification rules of the formData.age attribute can be used normally, otherwise the type verification will always fail. (there is actually a problem here, for example, if you are allowed to output a value in the form of 12ab, parseInt gets a value of 12.)

   has a more concise and rigorous description of type conversion:

"formData.age": [{type: "integer", message: "value is required to be an integer", trigger: "blur", transform:Number},},]

   means to convert to a numeric type, and that's fine. A value of 1.2or 12ab cannot pass the check.

In addition to type conversion,    transform can perform other processing, such as:

"formData.age": [{type: "string", pattern:/1/,message: "number required to be 1-100", transform (value) {return parseInt (value) > = 1 & & parseInt (value) = 1 & & parseInt (value) this.$t ("about")

   displays "about" in Chinese and "about" in English.

  , of course, you can also convert it to any other function, such as:

Message: () = > this.myMessageHandler (MessageId,paramValues) 4, advanced mode of rule verification

4.1.Asynchronous verifier asyncValidator

The    asynchronous validator is used for remote access, using ajax or axios request data, verifying response data or prompting exceptions.

   local page verification, which belongs to serial verification. Check the verification rules of each field one by one. If you fail, you will return the verification failure.

   remote check, for asynchronous check, multiple requests, response time is different, the sequence of responses can not be predicted.

The role of    asynchronous verification: the front-end and back-end can be used for the same attribute field, using the same verification rules, and the back-end can provide verification. But it also increases the cost of front-end communication and consistency maintenance.

The asynchronous validator is not currently used in   . Here is an example on the official website:

AsyncField1: {asyncValidator: myAsyncValidator}    myAsyncValidator can be placed similar to the validator position. Suppose you place it in data. Const myAsyncValidator = (rule, value, callback) = > {ajax ({url: "xx", value: value,}) .then (function (data) {callback ();}, function (error) {callback (new Error (error));});}

   Promise Asynchronous Field check:

Const myAsyncValidator = (rule, value) > {return ajax ({url: "xx", value: value,});}

The difference between    is that Promise asynchronous field validation requires the user to write .then / .catch processing logic, and callbacks are not supported.

   asynchronous check, also involving the Options attribute

Options: {first: true}

   first is true, which means that multiple asynchronous checks will no longer process other asynchronous checks if the first check fails.

4.2.Deep rules Deep rules

   for object Object or array Array check, need to be specific to each element (member), here we will use Deep rules.

   Deep rules involves two attributes, fields and defaultField.

  , such as the official website example (slightly modified according to the customary form):

Deep check of the    object:

Rules: {address: [{type: "object", required: true, options: {first: true}, fields: {street: [{type: "string", required: true}], city: [{type: "string", required: true}], zip: [{type: "string", required: true, len: 8, message: "invalid zip"}],},}] Name: [{type: "string", required: true}],}

Deep check of    array:

Rules: {roles: [{type: "array", required: true, len: 3, fields: {0: [{type: "string", required: true}], 1: [{type: "string", required: true}], 2: [{type: "string", required: true}],},}],}

The deep parity of the    array looks silly, each member has to set the verification rules, and for the dynamic array, I don't seem to know how to set it.

The    defaultField property gives us the means to uniformly set the field verification rules. This property can be used either on the check property field or on the fields.

   for example:

Rules: {urls: [{type: "array", required: true, defaultField: {type: "url"},}],}

How to set    if it is an array of objects? It can be done in the following ways:

Rules: {persons: [{type: "array", required: true, defaultField: {type: "object", required: true, fields: {address: [{type: "object", required: true, fields: {street: [{type: "string" Required: true}], city: [{type: "string", required: true}], zip: [{type: "string", required: true, len: 8, message: "invalid zip"}],},}], name: [{type: "string", required: true}] }],}

   array sets of objects, object sets of sub-objects, looks a little complicated.

4.3. Dynamic rule set

   sometimes enters the form in different modes and requires different rules to be applied. Such as new and editing operations, display the same page component. But at this time, the property fields that need to be verified on the page are different, how to set them?

   has two processing plans. Scheme 1 is to configure two sets of rule sets and switch according to different modes; scheme 2 is to configure the total rule set, extract appropriate attribute fields and rules according to different patterns, and build rule sets dynamically.

4.3.1. Switch check rule set

   switches the verification rule set. The sample code is as follows:

/ / data part / / current rule set rules: {}, / / Mode 1 rule set rules1: {.}, / / Mode 2 rule set rules2: {...}, / / methods part / / dynamic switch / / Page initialization init (obj Data) {this.prevForm = obj / / execute this.$nextTick (() = > {/ / reset all field values of the current page this.$refs ["form"] .resetFields () after this.visible = true; / / DOM update is visible on the settings page; if (data) {/ / Mode 1 this.form.patternType = 1 } else {/ / Mode 2 this.form.patternType = 2;} / / set the verification rule this.setValidRules (this.form.patternType);}}, setValidRules (patternType) {if (patternType = = 1) {this.rules = this.rules1 } else if (patternType = = 2) {this.rules = this.rules2;}}

In this way,    switches the set of verification rules according to different modes. To perform rule verification immediately when switching rules, you need to set the validate-on-rule-change of el-form to false, that is:

4.3.2. Dynamically build a set of verification rules

   dynamically builds the verification rule set. The sample code is as follows:

/ / data part / / current rule set rules: {}, / / complete rule set allRules: {"formData.loginName": [{required: true, message: "login cannot be empty", trigger: "blur"}, {validator:loginNameValidator, trigger: "blur"}] "formData.passwd": [{required: true, message: "password cannot be empty", trigger: "blur"}, {min: 6, max: 18, message: "password 6-18 digits", trigger: "blur"}], "formData.email": [{type: "email", message: "need to conform to email format" Trigger: "blur"}], genderLabel: [{required: true, message: "gender cannot be empty", trigger: "change"},], userTypeLabel: [{required: true, message: "user type cannot be empty", trigger: "change"},] DeptLabel: [{required: true, message: "Department cannot be empty", trigger: "change"},]}, / / methods part / / dynamic switch / / Page initialization init (obj,data) {this.prevForm = obj / / execute this.$nextTick (() = > {/ / reset all field values of the current page this.$refs ["form"] .resetFields () after this.visible = true; / / DOM update is visible on the settings page; if (data) {/ / Mode 1 this.form.patternType = 1 } else {/ / Mode 2 this.form.patternType = 2;} / / set the verification rule this.setValidRules (this.form.patternType) }}, setValidRules (patternType) {if (patternType = = 1) {/ / Mode 1 / / clear first, and then set this.rules = {}; this.rules ["genderLabel"] = this.allRules ["genderLabel"]; this.rules ["userTypeLabel"] = this.allRules ["userTypeLabel"] This.rules ["deptLabel"] = this.allRules ["deptLabel"]; this.rules ["formData.email"] = this.allRules ["formData.email"];} else {/ / Mode 2, need to verify login and password this.rules = {}; this.rules ["formData.loginName"] = this.allRules ["formData.loginName"] This.rules ["formData.passwd"] = this.allRules ["formData.passwd"]; this.rules ["genderLabel"] = this.allRules ["genderLabel"]; this.rules ["userTypeLabel"] = this.allRules ["userTypeLabel"]; this.rules ["deptLabel"] = this.allRules ["deptLabel"]; this.rules ["formData.email"] = this.allRules ["formData.email"] }}

   also needs to set the validate-on-rule-change of el-form to false.

4.4. Dynamic table field verification

Some forms in    use editable dynamic tables, such as adding a data row, enter data directly into the data row, and then submit it. At this point, the input of each field of the data row needs to be verified.

   has two plans.

   scenario 1 uses Deep rules's defaultField to perform field validation on an array of objects, as shown in the sample code above.

   scenario 2, which binds the field rule using the rules attribute at the el-form-item level.

4.5. Joint verification of multiple fields

   multi-field joint verification applications are relatively common, such as text start problems, different ID types, different verification rules; such as password verification, the two passwords should be the same; such as the purchase quantity cannot exceed the stock quantity, the start time of the time period should not be greater than the end time, and so on.

The key technique of    is to use the first parameter rule of the validator to add one or more custom attributes and pass the information to the validator for processing. The method of use is as follows:

As an example,    assumes that the "formData.email" field validation depends on the value of userType.

"formData.email": [{validator: idFieldWithTypeValidator, trigger: "blur",}]

There is no way to bind    initially:

"formData.email": [{validator: idFieldWithTypeValidator, trigger: "blur", "userType": this.form.formData.userype}]

   writes this, and the browser debugger displays an error indicating an error in calling resetFields.

Therefore, the correct form of    is:

"formData.email": [{validator: idFieldWithTypeValidator, trigger: "blur",}]

   or:

"formData.email": [{validator: idFieldWithTypeValidator, trigger: "blur", "userType": 0}]

   then dynamically sets the value of the userType property in the rule when the page is initialized, or in the chage event method where the selection box is changed:

This.rules ["formData.email"] [0] ["userType"] = this.form.formData.userType

   test results show that dynamic binding cannot be done with $set, that is, the following statements have no effect:

This.$set (this.allRules ["formData.email"] [0], "userType", this.form.formData.userType)

   is ready, and now you can write a joint validator idFieldWithTypeValidator. For simplicity, write in the data section:

Const idFieldWithTypeValidator = (rule, value, callback) = > {/ / get user type console.log (rule); return callback ();}

   test, output the rule print information in the browser console as follows:

{"userType": 2, "field": "formData.email", "fullField": "formData.email", "type": "string"}

   at this time, userType has been passed in through the rule parameter, and now you can perform joint verification.

Import {loginNameValidator,phoneNoValidator,idNoValidator,eMailValidator} from "@ / common/validator.js" export default {data () {/ / ID field verifier in different cases const idFieldWithTypeValidator = (rule, value, callback) = > {/ / get user type console.log (rule); if (rule.userType = = 1) {/ / Mobile phone number phoneNoValidator (rule, value, callback) } else if (rule.userType = = 2) {/ / ID number idNoValidator (rule, value, callback);} else if (rule.userType = = 3) {/ / email eMailValidator (rule, value, callback);}} return {.... }},...}

PhoneNoValidator, idNoValidator and eMailValidator are mobile phone number verifier, ID card number verifier and mailbox format verifier respectively, which are output from validator.js. According to the different values of userType parameters, the idFieldWithTypeValidator verifier invokes the relevant validator type verifier respectively. Of course, in the method code of idFieldWithTypeValidator, you can also move the code of each validator over without calling the external validator.

These are all the contents of the article "how to implement Vue Element-ui form validation rules". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 306

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report