赞
踩
在表单提交过程中很多时候要用到几个表单项二选一验证或多选一验证,比如联系方式中的手机号和固定电话只需要填写一项就可通过验证,针对这样情况可以使用Element-UI的自定义验证实现,具体实现方法如下。
HTML代码
- <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="form">
- <el-row :xs="24" style="width:96%">
- <el-col :span="8">
- <el-form-item label="简单:" prop="singleChoiceEasy" >
- <el-input v-model.number="ruleForm.singleChoiceEasy" placeholder="题量" @input="clearRule('singleChoiceDifficulty','singleChoiceMedium')"></el-input>
- </el-form-item>
- </el-col>
- <el-col :span="8">
- <el-form-item label="中等:" prop="singleChoiceMedium">
- <el-input v-model.number="ruleForm.singleChoiceMedium" placeholder="题量" @input="clearRule('singleChoiceDifficulty','singleChoiceEasy')"></el-input>
- </el-form-item>
- </el-col>
- <el-col :span="8">
- <el-form-item label="困难:" prop="singleChoiceDifficulty">
- <el-input v-model.number="ruleForm.singleChoiceDifficulty" placeholder="题量" @input="clearRule('singleChoiceEasy','singleChoiceMedium')"></el-input>
- </el-form-item>
- </el-col>
- </el-row>
- </el-form>
- data() {
- var validateNum= (rule, value, callback) => {
- if (!this.ruleForm.singleChoiceEasy && !this.ruleForm.singleChoiceMedium && !this.ruleForm.singleChoiceDifficulty) {
- callback(new Error('请至少填写一项'));
- } else {
- callback();
- }
- };
- return {
- ruleForm: {},
- rules: {
- singleChoiceEasy: [
- { required: true, validator: validateNum, trigger: 'blur' },
- { type: 'number', message: '必须为正整数', trigger: 'blur'}
- ],
- singleChoiceMedium: [
- { required: true, validator: validateNum, trigger: 'blur' },
- { type: 'number', message: '必须为正整数', trigger: 'blur'}
- ],
- singleChoiceDifficulty: [
- { required: true, validator: validateNum, trigger: 'blur' },
- { type: 'number', message: '必须为正整数', trigger: 'blur'}
- ]
- }
- }
- },
- methods: {
- clearRule(obj,obj1) {
- //接收参数 表单prop
- this.$refs.ruleForm.clearValidate(obj);
- this.$refs.ruleForm.clearValidate(obj1);
- }
- //另一种方式 表单@input 给他
- clearRule() {
-
- this.$refs.ruleForm.clearValidate();
- this.$refs.ruleForm.validateField(["singleChoiceEasy","singleChoiceMedium","singleChoiceDifficulty"]);
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。