如何在Vue的el-form中使用v-model和prop实现动态校验,包括多个变量控制校验、数组循环校验和字段级条件显示。通过实例演示了如何配合rules和自定义验证函数来确保表单的完整性和有效性。
公式: 动态校验项的v-model的绑定值 = el-form的属性 :model的值 + '.' + :prop属性的值
以此反推 :prop属性的值
此公式适应与element、element-plus、ant-design-vue组件库的表单校验
场景:本文是三种表单校验
1.多个变量控制某一项校验
2.对于数组for循环,校验每一项
3.对于两个不同的字段,分别v-if显示隐藏的校验
1. required: true 会有 * , 但仅是触发最后点击提交按钮时,校验某一项位必填;与输入事件或者选择或者失焦时候 怎么校验无关 (这时候的校验取决于是否写了具体的校验规则)为false则提交时可不填(默认false) 但是同时取决于validator的callback()返回是空还是返回报错提示
.
2.触发哪一条规则的校验和如何触发校验?
(1)触发哪一条规则的校验:
a、如果该el-form-item绑定了具体某个:rules=“rules.abc”,则触发abc的规则
b、默认取决于该el-form-item所绑定的prop字段,需要注意的是该prop属性在rules里必须要有,但是在form表单绑定的formData大对象里可有可无。
(2)如何触发该条校验:
取决于一级el-form-item下的子元素里的所有有的绑定了formData变量的元素和对应的trigger事件触发(所以可以多个输入框或选择框触发一项的校验事件)。需要注意该一级el-form-item下的子元素如果也包含了二级el-form-item和对应其他的prop,那么二级的el-form-item和对应其他的prop下的绑定变量和事件仅仅会触发二级自己的校验,而不会触发到一级的事件
一、多个变量控制某一项校验。
简单代码:重点在于prop="zdxx"自定义绑定和自定义校验事件
<el-form v-loading="loading" ref="ruleFormRef" :model="formData" :rules="rules" label-width="160px"
class="demo-ruleForm" :size="'default'" status-icon>
<el-row :gutter="24">
<el-col :span="12">
<el-form-item label="云主机名称:" prop="virtualMachineName">
<el-input placeholder="请输入" clearable />
</el-form-item>
</el-col>
<el-col :span="24">
<el-form-item label="站点信息:" prop="zdxx">
<el-col :span="12">
<el-checkbox :disabled="formData.applyVirtualMachineType === 2"
v-if="canEdit && formData.applyVirtualMachineType !== 2" v-model="formData.supportSiteAFlag" label="主调"
size="large" @change="changeCheckbox('siteAIp')" />
<el-checkbox disabled v-else v-model="formData.supportSiteAFlag" label="主调" size="large" />
</el-col>
<el-col :span="12">
<el-checkbox :disabled="formData.applyVirtualMachineType === 2"
v-if="canEdit && formData.applyVirtualMachineType !== 2" v-model="formData.supportSiteBFlag" label="备调"
size="large" @change="changeCheckbox('siteBIp')" />
<el-checkbox disabled v-else v-model="formData.supportSiteBFlag" label="备调" size="large" />
</el-col>
<el-col :span="12">
<template v-if="formData.supportSiteAFlag">
<el-form-item prop="siteAIp">
<el-input :disabled="formData.applyVirtualMachineType === 2"
v-if="canEdit && formData.applyVirtualMachineType !== 2" v-model="formData.siteAIp" placeholder="请输入"
clearable />
<span v-else>主调IP:<span class="ml">{{ formData.siteAIp }}</span></span>
</el-form-item>
</template>
</el-col>
<el-col :span="12">
<template v-if="formData.supportSiteBFlag">
<el-form-item prop="siteBIp">
<el-input :disabled="formData.applyVirtualMachineType === 2"
v-if="canEdit && formData.applyVirtualMachineType !== 2" v-model="formData.siteBIp" placeholder="请输入"
clearable />
<span v-else>备调IP:<span class="ml">{{ formData.siteBIp }}</span></span>
</el-form-item>
</template>
</el-col>
</el-form-item>
</el-col>
</el-row>
</el-form>
let formData = ref({
virtualMachineName: undefined,
// zdxx: [],
supportSiteAFlag: false,
siteAIp: undefined,
supportSiteBFlag: false,
siteBIp: undefined,
})
const isSite = (rule, value, callback) => {
if (!formData.value.supportSiteAFlag && !formData.value.supportSiteBFlag) {
callback(new Error('请选择站点信息'))
} else {
callback()
}
}
const rules = reactive({
virtualMachineName: [{ required: true, message: '请输入云主机名称', trigger: 'blur' },],
zdxx: [{ required: true, validator: isSite, trigger: 'change' },],
// supportSiteAFlag: [{ required: true, validator: isSite, trigger: 'change' },],
siteAIp: [{ validator: isIp1, trigger: 'blur' },],
// supportSiteBFlag: [{ required: true, message: '请选择备调', trigger: 'change' },],
siteBIp: [{ validator: isIp2, trigger: 'blur' },],
})
二、新增和删除表单项,动态校验。*
el-form表单动态动态新增表单进行校验。直接参考 动态增减表单项
以下代码可直接复制:重点在于:prop :rules :key。
公式: 动态校验项的v-model的绑定值 = el-form的属性 :model的值 + '.' + :prop属性的值根据公式倒推 :prop
例如:v-model=“domain.premium” 就是 dynamicValidateForm.premiumList[index].premium ,而且:model=“dynamicValidateForm”
所以得到 :prop = ‘premiumList.’ + index + ‘.premium’
<template>
<div>
<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="110px" class="demo-dynamic">
<div class="bor_box" v-for="(domain, index) in dynamicValidateForm.premiumList" :key="domain.key">
<el-col :span="24">
<div class="box4_div">
<el-col :span="5">
<el-form-item label="保费:" :prop="'premiumList.' + index + '.premium'" :rules="{required: true, message: '保费不能为空', trigger: 'blur'}">
<el-input class="num_input" placeholder="请输入" v-model="domain.premium"></el-input>
</el-form-item>
</el-col>
<el-col :span="5">
<el-form-item label="保费率:" :prop="'premiumList.' + index + '.rate'" :rules="{required: true, message: '保费率不能为空', trigger: 'blur'}">
<el-input class="num_input" placeholder="请输入" :precision="2" :step="0.01" v-model="domain.rate"></el-input>
</el-form-item>
</el-col>
<el-col :span="5">
<el-form-item label="上游费用率:" :prop="'premiumList.' + index + '.feeRate'" :rules="{required: true, message: '上游费用率不能为空', trigger: 'blur'}">
<el-input class="num_input" placeholder="请输入" :max="100" v-model="domain.feeRate"></el-input>
</el-form-item>
</el-col>
<el-col :span="5">
<el-form-item label="上游费用额:" :prop="'premiumList.' + index + '.fee'" :rules="{required: true, message: '上游费用额不能为空', trigger: 'blur'}">
<el-input class="num_input" placeholder="请输入" v-model="domain.fee"></el-input>
</el-form-item>
</el-col>
<el-col :span="4">
<el-button @click.prevent="removeDomain(domain,index)">删除</el-button>
</el-col>
</div>
</el-col>
</div>
<div>
<el-form-item>
<el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button>
<el-button @click="addDomain">添加保费</el-button>
<el-button @click="resetForm('dynamicValidateForm')">重置</el-button>
</el-form-item>
</div>
</el-form>
</div>
</template>
<script>
export default {
data () {
return {
dynamicValidateForm: {
premiumList: [{
selected: 'Y', premium: undefined, rate: undefined, feeRate: undefined, fee: undefined, baofei1_unit: '', shangyoufeiyonge_unit: '', downRate: undefined, downFee: undefined, xiayoufeiyonge_unit: '',
}],
},
}
},
created () {
},
methods: {
submitForm (formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!')
} else {
console.log('error submit!!')
return false
}
})
},
resetForm (formName) {
this.$refs[formName].resetFields()
},
removeDomain (item, index) {
if (index !== 0) {
this.dynamicValidateForm.premiumList.splice(index, 1)
}
},
addDomain () {
this.dynamicValidateForm.premiumList.push({
selected: 'N', premium: undefined, rate: undefined, feeRate: undefined, fee: undefined, baofei1_unit: '', shangyoufeiyonge_unit: '', downRate: undefined, downFee: undefined, xiayoufeiyonge_unit: '',
key: Date.now()
})
},
},
}
</script>
<style lang="less" scoped>
.bor_box {
margin-left: 50px;
margin-bottom: 10px;
overflow: hidden;
}
</style>
三、el-form表单校验v-if不生效、el-form表单校验v-show不生效:
例如有个表单项,通过控制显示两个不同的表单项内容,分别需要校验对应的表单项即可。
如果是直接用v-if,会发现切换时候,校验不生效;
如果直接使用v-show,又发现即使不切换,隐藏了另外的表单项,也会触发校验规则。
正确做法是:使用v-if控制表单项的显示隐藏,同时需要给el-form-item加上自己的 prop=" " 和 key=" " ,这样才能区分。当然:rules 也要有自己对应的提示。
<template v-if="flag">
<el-form-item label="姓名:" prop="name" key="name" :rules="rules.name">
<el-input v-model="formData.name" placeholder=""></el-input>
</el-form-item>
</template>
<template v-else>
<el-form-item label="退回原因:" prop="desc" key="desc" :rules="rules.desc">
<el-input type="textarea" maxlength="500" show-word-limit v-model="formData.desc" placeholder="请填写退回原因"></el-input>
</el-form-item>
</template>