Vue3+setup+validator verifies whether the two input passwords are consistent (local method)

data source:

const regForm = ref({
  name: '',
  email: '',
  password: '',
  passwordCheck: ''
})

Define two validator validation rules:

The first one here, that is, the if of validatepass2 can be in vue2:

if (this.regForm.passwordcheck !== '') {
       this.$refs.regForm.validateField('passwordcheck');
     }

But it is very troublesome to change this.$refs in vue3, so write it directly as follows:

const validatePass2 = () => {
  return (rule, value, callback) => {
    if (value !== regForm.value.password && regForm.value.password !== '') {
      callback(new Error('两次输入密码不一致!'))
    } else {
      callback()
    }
  }
}
const validatePass1 = () => {
  return (rule, value, callback) => {
    if (
      value !== regForm.value.passwordCheck &&
      regForm.value.passwordCheck !== ''
    ) {
      callback(new Error('两次输入密码不一致!'))
    } else {
      callback()
    }
  }
}

When using:

password: [
    {
      min: 6,
      max: 16,
      message: '密码长度在 6 到 16 个字符',
      trigger: 'blur'
    },
    { validator: validatePass1(), 
      trigger: 'blur'
    }
  ],
  passwordCheck: [
    {
      trigger: 'blur',
      message: '请确认密码'
    },
    { min: 6, 
      max: 16, 
      message: '密码长度在 6 到 16 个字符', 
      trigger: 'blur' },
    {
      trigger: 'blur',
      validator: validatePass2()
    }
  ]

There is a pit, extract validatePass1 and 2 to rules.js, and then import it will report an error of regForm undefined or regForm's .vale cannot be read, and it will take effect only after putting it in a file. The reason is not known yet.

Guess you like

Origin blog.csdn.net/m0_67987829/article/details/127640565