淘先锋技术网

首页 1 2 3 4 5 6 7

elementUI 中 Form 组件提供了表单验证的功能,只需要通过 rules 属性传入约定的验证规则,并将 Form-Item 的 prop 属性设置为需校验的字段名即可。

(1)常用表单验证

<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)自定义验证规则(关键字:validator)

 有些需要自定义的校验规则可以作为变量写在data中,然后赋值给validator字段

 

<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)动态表单验证

实际开发中很常见的需求,此时用rules、prop直接写就对应不上表单mode绑定的对象上的属性,所以需要用循环的方式找到要校验的字段所在数据中的索引,然后再以字符串拼接的方式连上校验字段名称:

 

 

<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  scoped>
.container{
	height: 100%;
	background-color: #fff;
	padding: 20px 100px;
	.line-item{
		/deep/.el-form-item__content{
			display: flex;
		}
	}
}	
</style>