无论是单纯的form-item循环还是把form-item放到表格的td中,其实都是在循环每个form-item,
校验的方式有如下两种:
<el-form
ref="formMsg"
label-width="0px"
class="form--label28"
:model="formMsg"
>
<div
class="card-wrapper p20 mb20"
v-for="(item, index) in formMsg.list"
:key="index"
>
<el-form-item
label="用途"
:prop="'formMsg.' + index + '.type'"
:rules='[{
required: true,
trigger: "change",
message: `请选择用途`
},{
validator: validateType, trigger: "change"
}]'
>
<el-select
v-model="item.type"
:options="options"
placeholder='请选择用途'
/>
</el-form-item>
</div>
</template>
</el-form>
注意: 绑定在el-form-item上的prop是唯一的 一一对于的 string类型的
data(){
return {
formMsg: {
list: [
{
type:''
},
{
type:''
}
]
}
}
},
methods: {
//这里的校验可以是同步的也可以是异步的
async validateType(rule, value, callback) {
const param = {};
const request = await $apis.XXX.XXXX(param)
const { code, msg } = request.data;
if (code == 1000) {
callback();
} else {
callback(new Error(msg));
}
},
submit(){
this.$refs.formMsg.validate((valid) => {
if (valid) {
console.log('校验成功');
return true
} else {
console.log('校验失败');
return false;
}
});
}
},
模版部分
<el-table-column
prop="name"
label="名称"
width="280"
class-name="td-name--first"
>
<template slot-scope="scope">
<el-form
:model="scope.row"
:rules="tableSpaceRules"
:ref="'name-' + scope.$index"
onkeydown="if(event.keyCode==13){return false;}"
>
<el-form-item prop="name">
<el-input
placeholder="请输入名称"
v-model="scope.row.name"
/>
</el-form-item>
</el-form>
</el-table-column>
规则直接写到data中
tableSpaceRules: {
name: [{
required: true,
trigger: "blur",
message: "请输入名称"
},
{
min: 1,
max: 30,
message: "最多 30 个字符",
trigger: "blur"
},
{
pattern: /^[A-Z]/,
message: "需以大写字母开头",
trigger: "blur"
},
{
pattern: /^[A-Z][A-Z0-9_]*$/,
message: "只能包含大写字母、数字和下划线",
trigger: "blur"
}
],
size: [
{ required: true, trigger: "blur", message: "请输入大小" },
{
pattern: /(^\d+$)/,
message: '只能包含数字',
trigger: "blur"
}
]
}
校验方法
submitTableForm(tableData, formName) {
let str = "";
let arr = [];
tableData.forEach((item, index) => {
str = formName + "-" + index;
this.$refs[str].validate(valid => {
if (valid) {
arr.push("1");
} else {
arr.push("0");
return false;
}
});
});
if (arr.includes("0")) {
return false;
} else {
return true;
}
},
verifyTableSpace() {
let nameFlag = this.submitTableForm(this.tableSpaceNameData, "name");
if (this.nameFlag) {
console.log("校验通过")
} else {
console.log("校验失败")
}
},