vue + ant design of vue表单校验实现方法总结
表单示例为FormModel表单
1.通过rules绑定,不需要自定义,适用于一般校验
html
<a-form-model
ref="ruleForm"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 15 }"
:model="formData"
:rules="rules"
>
<a-form-model-item label="用户名" prop="username" >
<a-input v-model="ruleForm.username" placeholder="请输入用户名"/>
</a-form-model-item>
<a-form-model-item label="用户名" prop="password" >
<a-input v-model="ruleForm.password" placeholder="请输入密码"/>
</a-form-model-item>
</a-form-model>
js
rules = {
username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
};
2.通过validator自定义校验
js
rules = {
username: [{ required: true, message: '请输入用户名', trigger: 'blur' },
{
pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, //自定义正则表达式校验
message: '仅支持中英文、数字和下划线',
},],
password: [{ required: true, message: '请输入密码', trigger: 'blur' },
{validator:this.validatePwd,trigger:'blur'}],
};
//自定义校验方法实现,自己进行一些特殊处理
private async validatePwd(rule: any, value: any, callback: any) {
if(value.length>5){
callback(new Error('密码长度不能超过5');
}else{
callback();
}
}
3.validate-status和help
通过validate-status和help来控制表单项的校验状态,绑定事件来触发校验,改变状态:
html
<a-form-model
ref="ruleForm"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 15 }"
:model="formData"
:rules="rules"
>
<a-form-model-item label="用户名" prop="username" >
<a-input v-model="ruleForm.username" placeholder="请输入用户名" />
</a-form-model-item>
<a-form-model-item label="用户名" prop="password" :validate-status="pwdStatus" :help="pwdError">
<a-input v-model="ruleForm.password" placeholder="请输入密码" @blur="validatePwd()"/>
</a-form-model-item>
</a-form-model>
js
var pwdStatus = '';
var pwdError = '';
validatePwd(){
if(this.ruleForm.password.length>5){
this.pwdStatus = 'error';
this.pwdError = '密码长度不能超过5';
}else{
this.pwdStatus = 'success';
this.pwdError = '';
}
}