本篇包含一般表单校验、自定义表单校验、多个表单校验
基础知识
- el-form 支持嵌套
- 可以单独给 form 绑定 rules,也可以给 form-item 绑定 rules
一般表单校验
| <el-form ref="serviceFormRef" :model="serviceForm" :rules="serviceRules" label-width="120px" label-position="top" class="form-input service-form" > <el-form-item label="名称:" prop="name"> <el-input v-model="serviceForm.ame" placeholder="请输入名称"></el-input> </el-form-item> </form>
|
| const serviceRules = reactive({ name: [ { required: true, message: '请输入服务名称', trigger: 'blur' }, { validator: validateText50RequiredWithSapce, trigger: ['blur', 'change'] } ] })
|
自定义表单校验
| <div class="error-info" v-if="showError">尚有内容未完成,请修改后提交</div>
|
| try { state.otherForm.hdConfigList.forEach((hd) => { if (!hd.accessory_id || !hd.value || hd.value == '') { throw new Error() } else { arr.push(hd) } }) } catch (e) { state.showError = true return }
|
多个表单校验
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| const checkForm = (formName) => { return new Promise<void>((resolve, reject) => { const formEl = unref(formName) formEl.validate((valid) => { if (valid) { resolve() } else reject() }) }) }
const handleSubmit = () => { let list = [] list.push(checkForm(configFormRef), checkForm(hdConfigListRef)) Promise.all(list) .then(() => { }) .catch((error) => { console.log('未通过', error) }) }
|