1. Problem description
During the project development process, form verification was encountered . The verification rules this time were relatively strict, and the verification that came with the element-ui form could not solve the problem at all.
2. Solution:
Use the custom verification in elementui form verification. validUsername is the name of the custom verification method.
2.1 Define form validation:
rules: {
userTypeId: [
{ required: true, message: '请选择类型', trigger: 'change' },
username:
{ required: true, validator: validUsername, trigger: 'blur' }
]
}
2.2 Custom verification method:
Note: The first definition in the method must return callback(), otherwise the form verification will not be successful.
export default {
name: 'Registry',
data() {
// js部分
const validUsername = (rule, value, callback) => {
const reg = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,18}$/
if (value === '') {
callback(new Error('请输入用户名'))
} else if (!reg.test(value)) {
callback(new Error('用户名必须是由6-18位英文(含大小写)+数字组成'))
} else {
callback()
}
}
}
}
3. Form verification
this.$refs.ruleForm.validate((valid) => {
if(valid){
console.log('表单校验成功')
}
})
4. Clear the form verification results.
The cancel button may be used.
this.$refs.pwdChangeForm.clearValidate()
Simple case: change password
Define form validation:
rules: {
newPassword: [
{ required: true, message: '新密码不能为空', trigger: 'blur' },
{ min: 8, max: 16, message: '长度在 8 到 16 个字符', trigger: 'blur' },
{ required: true, validator: toPassword, trigger: "blur" }
],
confirmPassword: [
{ required: true, message: "确认密码不能为空", trigger: "blur" },
{ required: true, validator: equalToPassword, trigger: "blur" }
]
},
Custom verification method:
Note: The first definition in the method must return callback(), otherwise the form verification will not be successful.
export default {
name: 'Registry',
data() {
// js部分
// 密码自定义校验
const toPassword = (rule, value, callback) => {
var passwordreg = /(?![A-Z]*$)(?![a-z]*$)(?![0-9]*$)(?![^a-zA-Z0-9]*$)/
if (!passwordreg.test(value)) {
callback(
new Error(
'密码必须由大写字母、小写字母、数字、特殊符号中的2种及以上类型组成!'
)
)
} else {
callback()
}
}
// 确认密码自定义校验
const equalToPassword= (rule, value, callback) => {
if (this.infoForm.newPassword !== value) {
callback(new Error("两次输入的密码不一致"));
} else {
callback();
}
}
}
}
Reference article: element-ui form custom verification_element form custom verification_Zheng Shixiu's blog-CSDN blog