/ 验证规则
rules: { // 多个验证用数组 单个验证用对象
// 验证账号
acc: [
{ required: true, message: '不能为空', trigger: 'blur' },
{ min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
],
pwd: [
{required: true, message: "密码不能为空", trigger: 'blur'},
{min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: 'blur'}
]
}
点击按钮时,验证表单
// 点击登录按钮
submitForm(){
// ui框架validate自带的方法 validate((valid)=>{ valid就是验证结果 });
this.$refs.loginForm.validate((valid)=>{
this.$refs.loginForm.validate((valid)=>{
if( valid ){
console.log("验证通过")
this.$message({
message: '恭喜你,登录成功',
type: 'success'
});
this.$router.push("/layout");
}else{
console.log("账号或者密码错误");
this.$message.error('账号或者密码错误');
}
});
});
},
自定义表单验证
1.在 data(){ 在return之前写验证函数 }
2.引入工具js文件 ,正则验证
import { PWD_REG } from '@/utils/reg.js'
data() {
// 验证原密码 3个参数
Rules 验证规则
Value 验证的值
Callback 回调函数
const checkOldPwd = (rules, value, callback) => {
!PWD_REG.test(value) // 加一个正则条件
if (!value) {
callback(new Error('原密码不能为空')) 错误提示
} else {
callback() 什么都不写,就是成功回调
}
}
return {
eiditForm: {
oldPwd: '',
newPwd: '',
newPwd2: '',
},
rules: {
oldPwd: { validator: checkOldPwd, trigger: 'blur' },
newPwd: { validator: checkNewPwd, trigger: 'blur' },
newPwd2: { validator: checkNewPwd2, trigger: 'blur' },
},
}
},
{ validator: 验证的函数, trigger: 'blur' },
按钮是通过什么来触发
Add(){
This.$refs.表单id.validate((valid)=>{ valid == 验证结果 })
}