Vue element UI form verification rules, what do you master?

Time:2022-5-9

1. Foreword

The element UI form verification rule enables the error prompt to be displayed directly under the form item without pop-up box, so it is still very easy to use.

After I checked the form of the login page, I once thought I knew the verification rules of the form very well. However, when I used the form verification rules in depth, I encountered the following problems:

  • How to judge whether the attribute value is within a certain range, and this range can be specified arbitrarily?
  • How to judge whether the attribute value is a certain value?
  • Multiple attributes are jointly verified. The verification rules of the current attribute depend on the value of another attribute. How to verify? For example, on the registration page, the ID types include email address, mobile phone number and ID card number. If different types are selected, the verification rules of idvalue attribute are different. How to deal with them?
  • In both modes, when entering the same form component, some fields can not use verification rules, that is, the objects of rules will be different. How to deal with this situation?

The above problems make me feel almost white. So I was forced to study the verification rules from the beginning and consult the relevant documents.

This article shares the experience of form verification rules.

2. Entry mode of rule verification

2.1. Example code

As an introduction to rule verification, take the login page as an example, and the code is as follows:

XX management system login
      
        
      
      
        
      
      
        
        
          
        
      
      
        Sign in
      
    
    



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", trigger: 'blur'}
        ],
        verifyCode: [
          {required: true, message: "verification code cannot be empty", trigger: 'blur'},
        ]
      }      
    };   
  },
  methods: {
    // 提交Sign in
    submitForm(formName) { 
      let _this = this;     
      //Perform verification
      this.$refs[formName].validate(valid => {
        //If the verification passes, it is true. If one fails, it is false
        if (valid) {
          //Pass verification
          // Sign in处理
          // ....
        } else {
          //Failed the verification
          console. Log ('validation failed ');
          return false;
        }
      });
    },
  }  
}

2.2 form item

Form item, indicating the use of verification rules:

: Rules = “rules” indicates that the verification rule uses the rule object. You can also use other names, such as rules1.

2.3. Prop item

Prop item, indicating which fields may use verification rules:

If the attribute value specified by the prop item, such as username, also has a corresponding item in the rules, it means that the attribute value performs rule verification. This attribute must be the attribute of the data object bound by the model attribute of the form. In this example, it is form, which is defined in data:

form: {
        username: "",
        password: "",
        verifyCode: "",
      },

2.4 rules

The rules item, that is, the verification rule set, is defined in data, and its name must be consistent with the rule object name bound by the: Rules attribute of the 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", trigger: 'blur'}
        ],
        verifyCode: [
          {required: true, message: "verification code cannot be empty", trigger: 'blur'},
        ]
      }

This is an object. The type of each element is: {attribute name: [rule]}. The attribute name is for the attribute value of prop. [rule] is a rule array. Each item of the rule array is a verification rule for this attribute.

2.5 rule item

Rule item, that is, the element of rule array, is the focus of this paper. Here, first analyze the element items of the above rules:

  • Required: indicates whether there must be a value. The value is true / false. If true, there must be a value. If there is no value, the verification fails; If it is false, no value is allowed, but if there is a value, it will not affect the use of other rules.
  • Message: prompt message. This message is prompted when the verification fails.
  • In general, trigger / input means that the focus is lost, and in general, trigger / input means that the focus is lost; Change is the value change, which is generally used in the selection box.
  • Min: minimum length of string.
  • Max: the maximum length of the string.

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

2.6 rules of use

this.$refs[‘form’].validate(valid => {
        //If the verification passes, it is true. If one fails, it is false
        if (valid) {
          //Pass verification
        } else {
          //Failed the verification
        }
      });

This validate method requires all verification rules to pass before release. Where, $refs [‘form’], refers to the ref attribute value of the form.

2.7 core of rule verification

  the core of rule verification is the async validator plug-in. Official website:https://github.com/yiminghe/async-validator。

   element UI uses the plug-in and encapsulates it. Official website:https://element.eleme.cn/#/zh-CN/component/form。

Therefore, the information on both sides will be helpful.

3. Advanced mode of rule verification

3.1. Nested object attribute name

Sometimes, prop is not a simple attribute, but an attribute wrapped under other objects. For example:

The form object bound to the model of the form. Its form is:

form:{
          //Form data field. For the convenience of submitting to the back end, it is recommended that the name be consistent with that of userinfo field
          formData    : {
            userId      : 0,
            loginName   : '',
            passwd      : '',
            // ...
          },

          //Current display value of user type selection box
          userTypeLabel : "",
          // ...
        },

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

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

In this way, the compilation will report an error!

The following forms shall be used:

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

That is, wrap it in single quotation marks or double quotation marks to become a string.

3.2. User defined validator

There are many related materials on the Internet about the user-defined validator, such as the validator commonly used for regular checking.

Rule definition method:

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

Represents’ formdata The loginname ‘attribute uses the verifier of loginnamevalidator. Considering the reuse of code, the custom verifier is generally turned into a JS file, which is convenient for other pages or projects.

In the / SRC / common / directory, create the validator JS file, the code is as follows:

/*Login verification*/
export function loginNameValidator(rule, value, callback){
  const reg= /^[a-zA-Z][\w-. @]*$/;
  if(value == '' || value == undefined || value == null){
    callback();
  }else {  
    if (!reg.test(value)){
      Callback (new error ('It is required to start with English letter, followed by alphanumeric and -. @ symbol ');
    }else {
      callback();
    }
  }
}

Import this validator in the Vue file JS file:

import {loginNameValidator} from '@/common/validator.js'

If you need to import multiple external validators, include multiple in {}, such as {loginnamevalidator, passwordvalidator}.

There is a small pit here. Let me mention it a little.

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

import {loginNameValidator} from '../../../common/validator.js'

As a result, there was a compilation error, saying ‘.. /.. /.. could not be found/ common/validator. JS’ file, so various path representation attempts failed. Finally, I used @ instead, because / bulid / webpack base. Alias is configured in conf.js, indicating @ indicates SRC directory.

Return to the user-defined validator in the form of:

function ValidatorFuncName(rule, value, callback)

Method name, optional.

In fact, its complete form is:

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

The parameters have the following meanings:

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

    console.log(rule);

    You can print the rule parameter to see that it is the object data of this rule.

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

  • Callback: callback function pointing to the end of verification. If the verification passes, call callback (). If it fails, the following forms are generally used:

Callback (new error ('specific prompt ');

Or prompt with parameters:

return callback(new Error(`${rule.field} must be lowercase alphanumeric characters`));

Note that string formatting is not enclosed in single quotation marks, but enclosed with “~” symbol.

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

util.format('%s must be lowercase alphanumeric characters', rule.field),

The util file contains the format method, which is called util TS file, in the Src / directory of the official website, this is a TS file, which can be used as a public method.

In fact, you can return an array of errors, namely errors, such as:

const errors = [];
      errors. Push (new error ('It is required to start with English letter, followed by alphanumeric and -. @ symbol ');
      errors. Push (new error ('3444 requires English ');
      return callback(errors);

However, from the actual effect, the form only displays the prompt in the first line. It is estimated that the form of element does not support displaying multiple lines of error information.

  • Source: it is the attribute object for calling verification. You can print it out and have a look.
  • Options, additional parameters, mainly predefined message formats, can also be printed out.

More complex calibrators can carry parameters, such as:

//Integer range value verification
export const intRangeValidator = (min, max) => (rule, value, callback) => {
  var isInRange = (value >= min) && (value <= max);
  const reg = /^-?\d+$/;
  var isInt = reg.test(value);
  if (isInRange && isInt){
    return callback();
  }else{
    Return callback (new error ('the integer [${min}, ${Max}] `) between ${min} and ${Max} is required);
  }
}

usage method:

'formData.age': [
        {validator: intRangeValidator(1,100), trigger: 'blur'}
      ],

Indicates that formdata The value range of the age attribute is an integer from 1 to 100.

The user-defined verifier validator provides a free space to play. It can use regular matching, numerical calculation, comparison and other operations for complex verification, so it is commonly used. However, using a custom validator validator sometimes seems too cumbersome.

The user-defined verifier validator does not have to be placed in an external file, but can also be placed in a Vue file.

Places placed in data but not included in return. There is no comma at the end.

const loginNameValidator = (rule, value, callback) => {
  const reg= /^[a-zA-Z][\w-. @]*$/;
  if(value == '' || value == undefined || value == null){
    callback();
  }else {  
    if (!reg.test(value)){
      Callback (new error ('It is required to start with English letter, followed by alphanumeric and -. @ symbol ');
    }else {
      callback();
    }
  }
}

Or defined directly in the rule:

'formData.loginName': [
            {required: true, message: "login name cannot be empty", trigger: 'blur'},
            {validator(rule, value, callback){
              const reg= /^[a-zA-Z][\w-. @]*$/;
              if(value == '' || value == undefined || value == null){
                callback();
              }else {  
                if (!reg.test(value)){
                  Callback (new error ('It is required to start with English letter, followed by alphanumeric and -. @ symbol ');
                }else {
                  callback();
                }
              }                
            }, 
             trigger: 'blur'}
          ],

3.3 type

The basic usage of type is as follows:

'formData.age': [
        {type: 'Integer', message: 'value should be an integer', trigger: 'blur'},
      ],

Type is also a rule item. If it does not meet the type requirements, an error message will be prompted.

The types supported by the rule are as follows:

  • String, string type, which is the default type. If the type is not specified, the default is string.
  • Number, number type. Includes integers and decimals.
  • Integer, integer type.
  • Float, floating point number type, cannot be an integer at this time, and must have a decimal point.
  • Boolean, boolean type, true / false value.
  • Array, array type.
  • Object, object type, cannot be array.
  • Enum, enumeration type, and then you need to declare the enumeration type.
  • Method, function (or method) type.
  • Regexp, regular type, must be a legal regular expression, which can be created through new regexp.
  • Date, date type, the value must be able to be converted to a valid date value.
  • URL, URL type, and value must conform to the URL format.
  • Email, email type, in line with the email format.
  • Hex, hexadecimal 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. These built-in types enable us to handle them without having to use the custom validator validator.

For numeric types (number, integer, float) and Boolean types, since the input is a string, type conversion must be carried out, otherwise the verification will fail. This involves the use of transform.

3.3 data conversion

Transform is a hook function that can process data before validation. As an example:

'formData.age': [
        {
            type: 'integer',
            Message: "the value must be an integer",
            trigger: 'blur',
            transform(value){return parseInt(value);},
        },
      ],

After transformation, formdata The verification rules of the age attribute can be used normally, otherwise it will always fail to pass the type verification. (there is actually a problem here. For example, it is allowed to output the value of 12ab, and parseInt gets the value of 12)

For type conversion, transform has more concise and strict expression:

'formData.age': [
    {
        type:'integer',
        Message: "the value must be an integer",
        trigger: 'blur',
        transform:Number},
    },
  ],

The representation is converted to a numeric type, which is all. Values of 1.2 or 12ab cannot pass the verification.

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

'formData.age': [
            {type: 'string', pattern: / 1 /, message: "the value should be 1-100", transform (value) {return parseInt (value) > = 1 & & parseInt (value) < = 100? "1": "0";},}
          ],

Equal to a value:

'formData.age': [
            {type: 'string', pattern: / 1 /, message: "value must be 50", transform (value) {return value = = "50"? "1": "0";},}
          ],

Not equal to a value:

'formData.age': [
        {type: 'string', pattern: / 0 /, message: "value cannot be 50", transform (value) {return value = = "50"? "1": "0";},}
      ],

3.4 value range

Range is not a regular attribute field, which is reflected by the min and Max attributes.

If the type is string or array, min and Max represent the length.

If the type is numeric (number, integer, float), min and Max represent the range of values. For example:

'formData.age': [
    {
        type:'integer',
        Message: "the value should be an integer from 1 to 100",
        min: 1,
        max:100,
        trigger:'blur',
        transform:Number,
    },
  ],

In this way, the range verification can directly use the built-in properties of the rule and be described in the rule, and there is no need for the intrangevalidator and regular matching method.

3.5 enumeration value

Usage examples of enumeration value types:

'formData.idType': [
            {
                Type: 'enum', enum: [2,4,6], message: 'result does not exist', trigger: [change ',' blur '], transform (value) {return number (value) * 2},
            },
          ],

Or:

'formData.gender': [
        {
            Type: 'enum', enum: ['male', 'female'], message: 'result does not exist', trigger: ['change', 'blur'],
        },
      ],

There are the following problems in using:

  • The response is relatively slow, that is, there is no verification for the first few inputs. Once there is verification, it can be done later.
  • For the latter case, that is, the set with the range of string, the verification is normal. For the former case, that is, if the range is integer, 0 also passes the verification, resulting in any string passing the verification. This is a bug.

Therefore, you can also use the string enumeration value to verify the range:

'formData.age': [
            {
                type : 'enum',
                enum:["1"],
                Message: "the value should be 1-100",
                transform(value){
                    if (!isNaN(value)){
                      return parseInt(value)>=1 && parseInt(value)<=100 ? "1" : "0";
                    }else{
                      return "0";
                    }
              	}
            },
          ],

Note: at this time, 1E3 and 9e811 are considered to have passed the verification, because the parseInt function only takes the number in front of E, while IsNaN considers it to be a number. It seems that it still needs to cooperate with the regular rules.

3.6 regular pattern

The pattern attribute is the regular expression matching verification rule, such as:

'formData.loginName': [
            {required: true, message: "login name cannot be empty", trigger: 'blur'},
            {pattern:/^[a-zA-Z][\w-. @]*$/,
             Message: 'the requirement is: the beginning of English letter, followed by alphanumeric and [email protected] Symbol ',
             trigger: 'blur'}
          ],

The effect is the same as that of the previous loginnamevalidator validator. The difference is that loginnamevalidator can be reused to maintain a regular verification. If it needs to be modified, only one change is needed. Using pattern is not. However, using pattern can reduce the writing of custom validators, giving users a choice.

Using the pattern attribute, you can verify that it is equal to a certain value.

Equal to a value:

{pattern: / 120 /, message: 'must be 120', trigger: 'blur'}

   for JS regular expressions, you can first test them with the JS regular expression online test tool to check whether they achieve the desired effect. JS regular expression online test address:https://c.runoob.com/front-end/854。

3.7 length len

Len attribute. If the type is string or array, it indicates the length. If it is numeric, it means that the numeric value is the len attribute value.

Len attribute appears simultaneously with min and Max attributes, and Len attribute has higher priority.

Len attribute, which can be used for formatted string verification, such as ID number length.

Len can also be used to verify that it is equal to a certain value, such as:

'formData.age': [
    {
        type:'integer',
        Message: "the value must be 6 years old",
        len: 6,
        trigger:'blur',
        transform:Number,
    },
  ],

3.8. Blank whitespace

Blank indicates a string composed of all spaces. The type of rule must be string. If the rule is matched, an alarm will appear. For example:

'formData.email': [
             {whitespace: true, message: 'only spaces exist', trigger: 'blur'}
          ],

If the value is blank, an alarm will be prompted.

If you do not want spaces to interfere with the verification, you can use transform:

transform(value) { return value.trim();}

3.9、i18n

The usage of imessage-18n integration, i.e. imessage-18n, supports Internationalization:

message: () => this.$t( 'about' )

“About” is displayed in Chinese language and “about” is displayed in English language.

Of course, you can also replace it with any other function, such as:

message: () => this.myMessageHandler(MessageId,paramValues)

4. Advanced mode of rule verification

4.1 asynchronous verifier asyncvalidator

Asynchronous verifier is used for remote access. It uses Ajax or Axios to request data, verify the response data or prompt exceptions.

Local page verification belongs to serial verification. Check the verification rules of each field one by one. If it fails, it will return to verification failure.

Remote verification is asynchronous verification. Multiple requests have different response times, and the order of response cannot be predicted.

Function of asynchronous verification: the front-end and back-end can use the same verification rules for the same attribute fields, and the verification is provided by the back-end uniformly. But this also increases the cost of front-end communication and consistency maintenance.

At present, the asynchronous verifier is not used. Here is an example from the official website:

asyncField1:{asyncValidator: myAsyncValidator}

Myasyncvalidator can be placed in a position similar to validator. Suppose it is placed 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 verification:

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

The difference is that promise asynchronous field verification needs to be written by the user then/. Catch processing logic does not support callback.

Asynchronous verification also involves the options attribute,

options: { first: true },

First is true, which means that multiple asynchronous verifications will not process other asynchronous verifications when the first verification fails.

4.2 deep rules

The verification of object or array array needs to be specific to each element (member), and deep rules are used here.

Deep rules involves fields and defaultfield attributes.

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

Deep validation of objects:

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 verification 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 verification of arrays looks silly. Each member should set verification rules. For dynamic arrays, it seems that they don’t know how to set them.

The defaultfield attribute enables us to uniformly set the field verification rules. This attribute can be used on the verification attribute field or fields.

For example:

rules : {
  urls: [{
    type: 'array',
    required: true,
    defaultField: { type: 'url' },
  }],
};

If it is an object array, how to set it? This can be done as follows:

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 set object, object set sub object, looks a little complicated.

4.3 dynamic rule set

Sometimes different rules need to be applied when entering a form in different modes. For example, add and edit operations, the same page component will be displayed. But at this time, the property fields to be verified on the page are different. How to set them?

There are two solutions. 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 dynamically build the rule set.

4.3.1. Switch verification rule set

Switch the verification rule set. The example code is as follows:

//Data part
      //Current rule set
      rules:{},
      //Pattern 1 rule set
      rules1:{
         ...
      },
      //Pattern 2 rule set
      rules2:{
          ...
      },

      //Methods section
      //Dynamic switching
      //Page initialization
      init(obj,data){
        this.prevForm = obj;

        //Settings page visible
        this.visible = true;

        //Execute after DOM update
        this.$nextTick(()=>{
          //Reset all field values of the current page
          this.$refs['form'].resetFields();

          if (data){
            //Mode 1
            this.form.patternType = 1;        
          }else{
            //Mode 2
            this.form.patternType = 2;
          }        
          //Set verification rules
          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, the verification rule set is switched according to different modes. In order 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. Dynamic construction of verification rule set

The verification rule set is built dynamically. The example code is as follows:

//Data part
      //Current rule set
      rules:{},
      //Complete set of rules
      allRules:{
          'formData.loginName': [
            {required: true, message: "login name 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: 'email format required', 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 section
      //Dynamic switching
      //Page initialization
      init(obj,data){
        this.prevForm = obj;

        //Settings page visible
        this.visible = true;

        //Execute after DOM update
        this.$nextTick(()=>{
          //Reset all field values of the current page
          this.$refs['form'].resetFields();

          if (data){
            //Mode 1
            this.form.patternType = 1;        
          }else{
            //Mode 2
            this.form.patternType = 2;
          }        
          //Set verification rules
          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,需要验证登录名和密码
          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'];
        }
      },

Similarly, you need to set the validate on rule change of El form to false.

4.4 dynamic table field verification

Some forms use editable dynamic tables, such as adding a data row, directly entering data in the data row, and then submitting. At this time, the input of each field in the data line needs to be verified.

There are two schemes.

Scheme 1 uses the defaultfield of deep rules to verify the field of the object array. See the example code above.

   scheme 2: bind the field rules with the rules attribute at the El form item level. See:https://www.jianshu.com/p/e51107b57366。

4.5. Multi field joint verification

Multi field joint verification is still common in applications, such as the problem of text beginning. Different ID types have different verification rules; If the password is verified, the two passwords shall be the same; For example, the purchase quantity cannot exceed the inventory quantity, and the start time of the time period should not be greater than the end time, etc.

The key technique is to use the first parameter rule of the verifier to add one or several custom attributes and transfer information to the verifier for processing. The usage is as follows:

As an example, suppose ‘formdata Email ‘field validation depends on the value of UserType.

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

There is no way to initial bind:

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

In this way, the browser debugger displays an error, prompting an error in calling resetfields.

Therefore, the correct form is:

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

Or:

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

Then, during page initialization, or in the chage event method selected by the selection box, dynamically set the value of UserType attribute in the rule:

this.rules['formData.email'][0]['userType'] = this.form.formData.userType;

The test results show that $set cannot be used for dynamic binding, that is, the following statements have no effect:

this.$set(this.allRules['formData.email'][0],'userType',this.form.formData.userType);

OK, 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 and output the print information of rule on the browser console as follows:

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

At this point, the UserType has been passed in through the rule parameter, and the joint verification can now be performed.

import {loginNameValidator,phoneNoValidator,idNoValidator,eMailValidator} from '@/common/validator.js'
  export default {
    data() {
      //ID field verifier under different types
      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 No
          idNoValidator(rule, value, callback);
        }else if(rule.userType == 3){
          // email
          eMailValidator(rule, value, callback);
        }
      }

      return {
          ....
      }            
    },
    ...
  }

Phonenovalidator, idnovalidator and emailvalidator are respectively the mobile number validator, ID Number Validator and email format validator, which is controlled by the validator JS, the idfieldwithtypevalidator validator respectively calls the validator of the relevant validator type according to the value of the UserType parameter. Of course, in the method code of idfieldwithtypevalidator, you can also move the code of each validator without calling the external validator.

The following are supplementary contents:

The disadvantages of the above solution, Yes, the rule is not attached to the attribute ‘UserType’ “The value is bound to the form.formdata.usertype property of data and cannot be linked. As a result, the modification of this.form.formdata.usertype needs to be set. Considering other situations, such as the verification of the sequence range of start date and end date, the change event of El input or El select brings more code overhead. Therefore, after considering, there is a new method, that is, the rule attachment property is a function method , this method can return this form. formData. The latest value of UserType.

The code is as follows:

//Under methods, add a getusertypevalue method
      getUserTypeValue(){
        return this.form.formData.userType;
      },

Rules part of data:

'formData.email': [            
             {validator : idFieldWithTypeValidator, trigger: 'blur','getValueFunc':this.getUserTypeValue,}
          ],

The getvaluefunc property is directly configured, and its value is the getusertypevalue method.

The code of validator idfieldwithtypevalidator is updated to:

//ID field verifier under different types
      const idFieldWithTypeValidator = (rule, value, callback) =>{
        //Method to get value
        var getvalueMethod= rule.getValueFunc;
        //Call the method to get the parameter value. You can return any type of data as needed, such as object, array, etc
        var userType = getvalueMethod();
        // console.log(userType);
        if (userType == 1){
          //Mobile phone number
          phoneNoValidator(rule, value, callback);
        }else if(userType == 2){
          //ID No
          idNoValidator(rule, value, callback);
        }else if(userType == 3){
          // email
          eMailValidator(rule, value, callback);
        }
      }

In this way, as long as there is a function method attached to the rule, there is no problem with the joint verification of any number of fields as needed. If necessary, getvaluefunc can return form Formdata object data or form object data is equivalent to providing the ability to access other data at will.

5. Reference articles

In addition to the official website, this article also refers to the following articles:

[1] Analysis of async validator source code,https://zhuanlan.zhihu.com/p/32306570?edition=yidianzixun&utm_source=yidianzixun&yidian_docid=0I5IikUl。

[2] Basic elements of element form verification in Vue,https://www.php.cn/js-tutorial-406545.html。

[3] , element UI form verification rules configuration,https://www.cnblogs.com/loveyt/archive/2020/07/11/13282518.html。

[4] Usage skills of element UI — detailed description of verification rules of form,https://www.cnblogs.com/xyyt/p/13366812.html。