element的表单验证用的是async-validator, 官方说明文档地址:https://github.com/yiminghe/async-validator;
element官网对表单验证只有简单的几个例子
这里记录下双层嵌套object数据的表单验证:
1. data中数据如下:
data(){
return{
ruleForm:{
human:{
name:'',
sex:0,
},
dog:'',
}
}
rules:{
dog: { required: true, message: '请填写dog', trigger: 'blur' }, //type默认是string
'human.name':[{type: "string", required: true, message: '请填写名字', trigger: 'blur'}], //有多条校验条件的时候可以放个object数组
'human.sex':{ type: "string",required: true, message: '请填写性别', trigger: 'blur'},
},
}
需要注意的是: 在async-validator官网中, object嵌套的时候rules也是个嵌套的结构:
但是我试下下, 这个格式无法识别. 不知道是不是我哪里有问题.
2. template中代码:
需要注意的是prop中, human下的属性, 要加上前缀"human.", dog直接写dog, 也就是是从rulesForm下开始算起
基本信息
确定
取消
3. 提交方法中:
methods:{
submitForm(formName) {
var self = this;
this.$refs[formName].validate((valid) => {
if (valid) { //提交前校验以下是否通过 self.$http.post(this.HOST+"/xxx",JSON.stringify(self.ruleForm.human), {headers: {"Content-Type": "application/json"}}) //我这里只提交human部分
.then(res=>{
}).catch(err => {
});
} else { //这一段是为了找到第一个校验不通过的地方, 然后focus过去
var isError=document.getElementsByClassName("is-error");
isError[0].querySelector('input').focus();
return false;
}
});
},
}