Typical example of Vue two field joint verification — changing password

Time:2022-5-8

1. Foreword

  this article is the foregoing《Vue element UI form verification rules, what do you master?》For the typical application of multi field joint verification.

When changing the password, you generally need to confirm that the password is the same twice, involving two attribute fields. Similar cases involving two attribute fields are:

  • Date time range. If both have values, it is required that: end time > = start time.
  • Quantity relationship: quantity lower limit < = quantity upper limit.

The characteristic is that both attribute values are variable. Based on the application of verifying the consistency of two passwords, this paper gives a typical solution of joint verification between two fields with variable attribute values.

2. Scheme realization

2.1 implementation code

Give the code of the form first:

User management / password modification
    
        
    
      
        
          
          
        
         
      
        
          
        
         
      
        
          
        
         
      
        determine
        cancel
            
    
  


  import {passwordValidator} from '@/common/validator.js'
  export default {
    data() {
      //Compare whether the two passwords are the same
      const comparePasswdValidator = (rule, value, callback) =>{
        //Method to get value
        var getvaluesMethod = rule.getValuesMethod;
        //Call getvaluesmethod method to get the object value
        var formData = getvaluesMethod();
        
        //One of them is empty. There may be no entered value yet. No comparison is made at this time
        if (formData.newPasswd == '' || formData.confirmPasswd == ''){
          return callback();
        }

        // ===========================================================
        //Compare passwords twice

        //Both have values. Compare them
        if (formData.newPasswd == formData.confirmPasswd){
          //The new password is consistent with the confirmation password
          //Clear the verification alarm prompt of two passwords first in order to clear the prompt of inconsistency of another password
          this.$refs['form'].clearValidate(['newPasswd','confirmPasswd']);
          callback();
        }else{
          Callback (new error ('two passwords are inconsistent ');
        }
      }

      return {
        form : {
          oldPasswd : '',
          newPasswd : '',
          confirmPasswd : ''
        },
        //Used to change the input type
        password:"password",  
        //Used to replace the icon in the input
        icon:"el-input__icon el-icon-view", 
        //Verification rule configuration
        rules: {
          oldPasswd : [
            {required: true, message: "password cannot be empty", trigger: 'blur'}
          ],          
          newPasswd : [
            "Required: '{, required:', cannot be null",
            {Min: 6, Max: 18, message: "new password 6-18 digits", trigger: 'blur'},
            {validator: passwordValidator, trigger: 'blur'},
            {validator: comparePasswdValidator,trigger: 'blur','getValuesMethod':this.getValuesMethod},
          ],     
          confirmPasswd : [
            {required: true, message: "confirm password cannot be empty", trigger: 'blur'},
            {Min: 6, Max: 18, message: "confirm password 6-18 digits", trigger: 'blur'},
            {validator: passwordValidator, trigger: 'blur'},
            {validator: comparePasswdValidator,trigger: 'blur','getValuesMethod':this.getValuesMethod},
          ],                   
        },        
      }
    },
    methods: {
      //The method of obtaining the value is used by all validators that need multi field joint verification
      getValuesMethod(){
        return this.form;
      },

      //Hiding and displaying passwords
      showPassword(){
        //Click the icon to hide or display the password
        if( this.password=="text"){
            this.password="password";
            //Replace Icon
            this.icon="el-input__icon el-icon-view";
        }else {
            this.password="text";
            this.icon="el-input__icon el-icon-stopwatch";
        }
      },
      
      //Submit
      submit(){
        let _this = this;
        this.$refs['form'].validate(valid => {
          //If the verification passes, it is true. If one fails, it is false
          if (valid) {
            _this.instance.changePasswd(_this.$baseUrl,_this.form).then(res => {
              if (res.data.code == _this.global.SucessRequstCode){
                //Prompt modification succeeded
                Alert ("reset password succeeded!");
                //Jump to home page
                this.$router.push({
                  path: '/home',
                });                
              }else{
                if (!_this.commonFuncs.isInterceptorCode(res.data.code)){
                  alert(res.data.message);
                }
              }              
            }).catch(error => {
              console.log(error);
            }); 
          }          
        })
      },

      // cancel
      cancel(){
        //Jump to home page
        this.$router.push({
          path: '/home',
        });            
      }
    }
  }

The imported external validator passwordvalidator is in / SRC / common / validator JS file, the code is as follows:

/*Password verification*/
export function passwordValidator(rule, value, callback) {
  const reg =/^[[email protected]#%&*!\-$^]+$/;
  if(value == '' || value == undefined || value == null){
    callback();
  } else {
    if (!reg.test(value)){
      Callback (new error ('password is composed of English letters, numbers and the following characters: @. #%& *! - $^ ');
    } else {
      callback();
    }
  }
}

2.2 code description

2.2.1. Rule configuration:

//Verification rule configuration
    rules: {
      oldPasswd : [
        {required: true, message: "password cannot be empty", trigger: 'blur'}
      ],          
      newPasswd : [
        "Required: '{, required:', cannot be null",
        {Min: 6, Max: 18, message: "new password 6-18 digits", trigger: 'blur'},
        {validator: passwordValidator, trigger: 'blur'},
        {validator: comparePasswdValidator,trigger: 'blur','getValuesMethod':this.getValuesMethod},
      ],     
      confirmPasswd : [
        {required: true, message: "confirm password cannot be empty", trigger: 'blur'},
        {Min: 6, Max: 18, message: "confirm password 6-18 digits", trigger: 'blur'},
        {validator: passwordValidator, trigger: 'blur'},
        {validator: comparePasswdValidator,trigger: 'blur','getValuesMethod':this.getValuesMethod},
      ],                   
    },

The key points are newpasswd and confirmpasswd attributes. Both are configured with the same rule set, and the verification rules are:

  • Value cannot be empty.
  • The length is 6-18 bits.
  • It complies with the rule of password validator, that is, the password is composed of English letters, numbers and the following characters: @. #%& *! – $^.
  • Compare the password verifier comparepasswdvalidator. This verifier adds a custom attribute getvaluesmethod, and the getvaluesmethod method with the attribute value of this. Note that it is a method, not a method name. This rule requires a getvaluesmethod method in methods and implements the comparepasswdvalidator validator.

These rules work together. Only when all rules pass the verification can the attribute verification pass, and the detection order is executed according to the order of the array.

In the verification rule, the newpasswd and confirpasswd attributes are configured with the same comparepasswdvalidator because the attribute values of the two fields are variable. Comparepasswdvalidator is at the end of the rule, that is, it needs to meet the previous verification rules first.

2.2.2 getvaluesmethod method

//The method of obtaining the value is used by all validators that need multi field joint verification
  getValuesMethod(){
    return this.form;
  },

Getvaluesmethod method returns the form data object in data. This is a very sharp operation, which is equivalent to providing a global data probe. The form data object of data can be accessed in the verifier. Due to the v-modal model of form, the real-time performance of data is ensured, that is, there is no need to worry about not obtaining the latest values of other attributes. Getvaluesmethod method provides an alternative idea of data binding.

2.2.3 comparepasswdvalidator

//Compare whether the two passwords are the same
  const comparePasswdValidator = (rule, value, callback) =>{
    //Method to get value
    var getvaluesMethod = rule.getValuesMethod;
    //Call getvaluesmethod method to get the object value
    var formData = getvaluesMethod();
    
    //One of them is empty. There may be no entered value yet. No comparison is made at this time
    if (formData.newPasswd == '' || formData.confirmPasswd == ''){
      return callback();
    }

    // ===========================================================
    //Compare passwords twice

    //Both have values. Compare them
    if (formData.newPasswd == formData.confirmPasswd){
      //The new password is consistent with the confirmation password
      //Clear the verification alarm prompt of two passwords first in order to clear the prompt of inconsistency of another password
      this.$refs['form'].clearValidate(['newPasswd','confirmPasswd']);
      callback();
    }else{
      Callback (new error ('two passwords are inconsistent ');
    }
  }

Because the configured custom rule attribute ‘getvaluesmethod’ points to this Getvaluesmethod, so this property can be called as a method:

//Method to get value
    var getvaluesMethod = rule.getValuesMethod;
    //Call getvaluesmethod method to get the object value
    var formData = getvaluesMethod();

The call result of the method property returns a pointer to this Form, so you can access the properties of the object at will.

Before comparing the two, if one is found to be empty, return. Because after the current attribute has entered a value, the opposite attribute may not have entered a value, so it should not be compared at this time.

//One of them is empty. There may be no entered value yet. No comparison is made at this time
    if (formData.newPasswd == '' || formData.confirmPasswd == ''){
      return callback();
    }

Two password comparisons:

// ===========================================================
    //Compare passwords twice

    //Both have values. Compare them
    if (formData.newPasswd == formData.confirmPasswd){
      //The new password is consistent with the confirmation password
      //Clear the verification alarm prompt of two passwords first in order to clear the prompt of inconsistency of another password
      this.$refs['form'].clearValidate(['newPasswd','confirmPasswd']);
      callback();
    }else{
      Callback (new error ('two passwords are inconsistent ');
    }

Compare the two passwords. If the two passwords are consistent, the alarm prompt will be output. If it is consistent, you need to clear the alarm prompt of the opposite end first, because there may be a prompt of “inconsistent password twice” at the opposite end.

//Clear the verification alarm prompt of two passwords first in order to clear the prompt of inconsistency of another password
      this.$refs['form'].clearValidate(['newPasswd','confirmPasswd']);

Clearvalidate method is the method of element form, which is used to clear the exception prompt of one or more verification rule attributes.

At this time, Is there a “false kill” situation? That is, the clearing operation will also clear other exception prompts at the opposite end. Considering that the two passwords are the same at this time, and the verification rules of the two are the same, since this verification rule is the last, in terms of detection order, it is the last to be executed, that is, when this verifier is executed, other verifications pass. Therefore, this “false kill” “Will not happen. So will the actual implementation effect.

In addition, it should be noted that the following code cannot be used to replace the clearvalidate call statement above at this time:

//Perform end-to-end verification
          if (rule.field == 'newPasswd')
          {
            //If the current property is newpasswd
            this.$refs['form'].validateField('confirmPasswd');
          }else{
            this.$refs['form'].validateField('newPasswd');
          }

Because the verification is being performed at this time, and then calling the opposite end verification will lead to the opposite end calling comparepasswdvalidator. If the two passwords are found to be the same in the opposite end verification results, the opposite end (the opposite end of the opposite end, i.e. itself) verification will be called again, so the loop is dead, resulting in call stack overflow. Therefore, in the verifier code, try not to call the validatefield method again.

2.3 verification effect

Here are some renderings:

Initial state:

Typical example of Vue two field joint verification -- changing password

Change the confirmation password and leave the input focus:

Typical example of Vue two field joint verification -- changing password

Enter the new password input box, leave the input focus without entering:

Typical example of Vue two field joint verification -- changing password

Modify the confirmation password, delete the character “8” at the end, leave the input focus, and return to the initial state at this time.