有些需要自定义的校验规则可以作为变量写在data中:
data() {
let reg = /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%^&*?]{6,12}$/
var validateNewPwd = (rule, value, callback) => {
if (!reg.test(value)) {
callback(new Error('密码应是6-12位数字、字母或字符!'))
} else if (this.form.oldPasswd === value) {
callback(new Error('新密码与旧密码不可一致!'))
} else {
callback()
}
}
var validateComfirmPwd = (rule, value, callback) => {
if (!reg.test(value)) {
callback(new Error('密码应是6-12位数字、字母或字符!'))
} else if (this.form.newPasswd !== value) {
callback(new Error('确认密码与新密码不一致!'))
} else {
callback()
}
}
return {
form: {
newPasswd: '',
comfirmPwd: ''
},
rules: {
newPasswd: [
{ required: true, message: '请输入新密码', trigger: 'blur' },
{ validator: validateNewPwd, trigger: 'blur' }
],
comfirmPwd: [
{ required: true, message: '请输入确认密码', trigger: 'blur' },
{ validator: validateComfirmPwd, trigger: 'blur' }
]
}
}
}
该方法转载于https://segmentfault.com/a/1190000020410128?utm_source=tag-newest,更多方法详见该网址
element-ui表单加判断条件显示必填或非必填 :required
一般情况我们是把required写在rules里,来说明表单内容是否是必填项,但是有些内容,不同情况,可能是必填,可能是非必填,因此需要加判断条件,此时,required 写在 el-form-item 中,data中的rule不用写 required
<el-form-item :label="省份" prop="provinces" :required="from.country === 'CHN'? true:false>
<el-input v-model.trim="from.provinces" size="mini" :disabled="See">
</el-form-item>
Rules: {
provinces: [{ validator: provinces, trigger: 'blur' }]
}