需求:
表单是循环出来的,3个一组,每组对于前端来说是一样的,
需要校验输入框是否必填+是否为小数或者整数
效果:
未输入--显示:请输入
输入不是小数或整数--显示:请输入整数或小数
输入正确:不提示错误信息
template:
主要是每个el-form-item绑定prop带上index
<el-form :label-position="labelPosition" label-width="140px" ref="predictionFormRef" :rules="predictionRules" :model="formLabelAlign">
<div class="zs-card zs-space-bottom" v-for="(obj, objIndex) in formLabelAlign.group" :key="objIndex">
<el-form-item label="月份:" :prop="'group.' + objIndex + '.month'" :required="true">
<el-input class="zs-full-item" v-model="obj.month" placeholder=" " :disabled="true" />
</el-form-item>
<el-form-item label="销售预算:" :prop="'group.' + objIndex + '.salesBudget'" :required="true">
<el-input class="zs-full-item zs-input-group-md" v-model="obj.salesBudget" placeholder=" " :disabled="true">
<template #append><div>万元</div></template>
</el-input>
</el-form-item>
<el-form-item label="销售预测:" :prop="'group.' + objIndex + '.salesPredict'" :rules="predictionRules.salesPredict">
<el-input class="zs-full-item zs-input-group-white zs-input-group-md" v-model="obj.salesPredict" placeholder="请输入" :disabled="isReadOnly">
<template #append><div>万元</div></template>
</el-input>
</el-form-item>
</div>
</el-form>
data:
let formLabelAlign = ref({
group: []
})
methods:
校验必填+数据格式:
const checkNumber = (rule, value, callback) => {
if (isNumberRegex(value)) {
callback()
} else {
callback(new Error('请输入整数或小数'))
}
}
let predictionRules = reactive({
salesPredict: [
{
required: true, message: '请输入', trigger: 'blur'
},
{
validator: checkNumber, trigger: 'blur'
}
]
})
提交表单时的校验:
const confirmClick = () => {
let formList = [predictionFormRef]
let resultArr = [];
let validate = (form) => {
let result = new Promise((resolve, reject) => {
form.value.validate(valid => {
if (valid) {
resolve()
} else {
reject()
}
})
})
resultArr.push(result)
}
formList.forEach(item => {
validate(item)
})
Promise.all(resultArr).then(() => {
saveRule() // 校验成功之后 保存数据的方法
})
}