dynamic form validation of elementUI form validation

The Form component in elementUI provides the form validation function. You only need to  rules pass in the agreed validation rules through attributes and  prop set the properties of Form-Item to the field names that need to be verified.

(1) Common form verification

<template>
	<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
		  <el-form-item label="活动名称" prop="user">
			<el-input v-model="ruleForm.user"></el-input>
		  </el-form-item>
		  
		  <el-form-item label="活动名称" prop="password">
		  	<el-input v-model="ruleForm.password"></el-input>
		  </el-form-item>
		
		  <el-form-item>
			<el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
			<el-button @click="resetForm('ruleForm')">重置</el-button>
		  </el-form-item>
	</el-form>
</template>

<script>
  export default {
    data() {
      return {
        ruleForm: {
          user: '',
          password: '',
        },
        rules: {
          user: [
            { required: true, message: '请输入账号', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'change' },
			{ min: 8, max: 16, message: '长度在 8 到 16 个字符', trigger: 'blur' }
          ],
        }
      };
    },
    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();
      }
    }
  }
</script>

(2) Custom validation rules (keyword: validator)

 Some validation rules that need to be customized can be written in data as variables and then assigned to the validator field.

 

<template>
	<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
		  <el-form-item label="密码" prop="pass">
		    <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
		  </el-form-item>
		  <el-form-item label="确认密码" prop="checkPass">
		    <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
		  </el-form-item>
		  <el-form-item label="年龄" prop="age">
		      <el-input v-model.number="ruleForm.age"></el-input>
		  </el-form-item>
			
		  <el-form-item>
		    <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
		    <el-button @click="resetForm('ruleForm')">重置</el-button>
		  </el-form-item>
	</el-form>
</template>

<script>
export default {
    data() {
      var checkAge = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('年龄不能为空'));
        }
        setTimeout(() => {
          if (!Number.isInteger(value)) {
            callback(new Error('请输入数字值'));
          } else {
            if (value < 18) {
              callback(new Error('必须年满18岁'));
            } else {
              callback();
            }
          }
        }, 1000);
      };
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm.checkPass !== '') {
            this.$refs.ruleForm.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        ruleForm: {
          pass: '',
          checkPass: '',
          age: ''
        },
        rules: {
          pass: [
            { required: true, validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            { required: true, validator: validatePass2, trigger: 'blur' }
          ],
          age: [
            { required: true, validator: checkAge, trigger: 'blur' }
          ]
        }
      };
    },
    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();
      }
    }
}
</script>

(3) Dynamic form verification

It is a very common requirement in actual development. At this time, writing directly using rules and prop cannot correspond to the attributes on the object bound to the form mode. Therefore, you need to use a loop to find the index in the data where the field to be verified is located, and then Concatenate the verification field names by string concatenation:

 

 

<template>
	<div class="container">
		<el-form :model="form" ref="formRef" label-width="100px">
		  <el-form-item
		    prop="email"
		    label="邮箱"
		    :rules="[
		       { required: true, message: '请输入邮箱地址', trigger: 'blur' },
		       { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
		    ]">
		    <el-input v-model="form.email"></el-input>
		  </el-form-item>
		  
		  <el-form-item class="line-item"
		    v-for="(item, index) in form.domains"
		    :label="'域名' + index"
		    :key="item.key"
		    :prop="'domains.' + index + '.value'"
		    :rules="{
		      required: true, message: '域名不能为空', trigger: 'blur'
		    }">
		    <el-input v-model="item.value"></el-input>
			<el-button @click.prevent="removeDomain(index)">删除</el-button>
		  </el-form-item>
		  
		  <el-form-item>
		    <el-button type="primary" @click="submitForm('formRef')">提交</el-button>
		    <el-button @click="addDomain">新增域名</el-button>
		    <el-button @click="resetForm('formRef')">重置</el-button>
		  </el-form-item>
		</el-form>
	</div>
</template>

<script>
export default {
    data() {
        return {
			form: {
			  domains: [{
				value: ''
			  }],
			  email: ''
			}
        };
    },
    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(index) {
			this.form.domains.splice(index, 1)
        },
        addDomain() {
            this.form.domains.push({
               value: '',
               key: Date.now()
            });
        }
    }
}
</script>


<style lang="less" scoped>
.container{
	height: 100%;
	background-color: #fff;
	padding: 20px 100px;
	.line-item{
		/deep/.el-form-item__content{
			display: flex;
		}
	}
}	
</style>

Guess you like

Origin blog.csdn.net/to_prototy/article/details/129454357