elementUI表单验证
程序员文章站
2022-03-04 11:34:53
...
1、js
import store from '@/store'
// 自定义验证条件
// 手机号验证规则
const verifyPhone=(str)=>{
const reg=/^1\d{10}$/;
return reg.test(str);
}
//验证手机号码
const validPhone=(rule,value,callback)=>{
if(!value){
callback(new Error('请输入手机号'));
}else if(!verifyPhone(value)){
callback(new Error('请输入正确的11位手机号码'));
}else{
callback();
}
}
// 验证非必填手机号
const validNoRequiredPhone=(rule,value,callback)=>{
if(value && !verifyPhone(value)){
callback(new Error('请输入正确的11位手机号码'));
}else{
callback();
}
}
//验证确认密码
const validPass2 = (rule, value, callback) => {
if (!value) {
callback(new Error('请再次输入密码'));
} else if (value !== store.state.password) {
callback(new Error('两次输入密码不一致!'));
} else {
callback();
}
};
// 验证年龄
const validAge=(rule,value,callback)=>{
if(typeof value!='number'){
callback(new Error('请输入数字'));
}else{
callback();
}
}
// 验证表单规则
const rules={
username:{ required:true, trigger:'blur',validator:validPhone },
password: { required:true, message:'请输入密码', trigger:'blur' },
rePswd:{required:true,trigger:'blur',validator:validPass2},
adress:{ required:true,message:'请选择地址',trigger:'change' },
age:[
{ required:true,message:'请输入年龄',trigger:'blur' },
{trigger:'blur',validator:validAge}
]
}
2、vue
<el-form ref="form" :model="form" :rules="rules">
<el-form-item prop="username">
<el-input v-model="form.username" placeholder="手机号"></el-input>
</el-form-item>
</el-form>
3、手动取消表单某一项验证
this.$refs['refEl'].clearValidate();
下一篇: ElementUi表单rules验证