Form Validation in Element-UI

insert image description here

  Element is a Vue 2.0-based desktop component library for developers, designers and product managers.
  Element has prepared corresponding Element plug-ins for vue-cli. Developers can use them to quickly build an Element-based project. Not only can they quickly experience the interaction details, but they can also use the code encapsulated by the front-end framework for rapid development.
  As a front-end framework, Element-UI is most commonly used for form validation. Form validation is to allow users to discover and correct errors as early as possible on the premise of preventing users from making mistakes. Form validation in Element-UI mainly has the following methods:

1. Form validation for all fields

  It is suitable for checking all fields of the form or for simple data types that need to check the field type.
  The Form component provides the form validation function, you only need to pass in the agreed validation rules through the rules attribute, and set the prop attribute of Form-Item to the field name to be validated. The rules will check the value in the prop according to the rules given by the rules, and when the requirements are not met, the corresponding prompt message of the message will pop up.
  The sample code is as follows:

<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
  <el-form-item label="活动名称" prop="name">
    <el-input v-model="ruleForm.name"></el-input>
  </el-form-item>
  <el-form-item label="活动区域" prop="region">
    <el-select v-model="ruleForm.region" placeholder="请选择活动区域">
      <el-option label="区域一" value="shanghai"></el-option>
      <el-option label="区域二" value="beijing"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="活动时间" required>
    <el-col :span="11">
      <el-form-item prop="date1">
        <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.date1" style="width: 100%;"></el-date-picker>
      </el-form-item>
    </el-col>
    <el-col class="line" :span="2">-</el-col>
    <el-col :span="11">
      <el-form-item prop="date2">
        <el-time-picker placeholder="选择时间" v-model="ruleForm.date2" style="width: 100%;"></el-time-picker>
      </el-form-item>
    </el-col>
  </el-form-item>
  <el-form-item label="即时配送" prop="delivery">
    <el-switch v-model="ruleForm.delivery"></el-switch>
  </el-form-item>
  <el-form-item label="活动性质" prop="type">
    <el-checkbox-group v-model="ruleForm.type">
      <el-checkbox label="美食/餐厅线上活动" name="type"></el-checkbox>
      <el-checkbox label="地推活动" name="type"></el-checkbox>
      <el-checkbox label="线下主题活动" name="type"></el-checkbox>
      <el-checkbox label="单纯品牌曝光" name="type"></el-checkbox>
    </el-checkbox-group>
  </el-form-item>
  <el-form-item label="特殊资源" prop="resource">
    <el-radio-group v-model="ruleForm.resource">
      <el-radio label="线上品牌商赞助"></el-radio>
      <el-radio label="线下场地免费"></el-radio>
    </el-radio-group>
  </el-form-item>
  <el-form-item label="活动形式" prop="desc">
    <el-input type="textarea" v-model="ruleForm.desc"></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>

  In this way, you need to write rule{} in data(), and write the verification rules in the fields that need to be verified in the prop. The sample code is as follows:

<script>
  export default {
    
    
    data() {
    
    
      return {
    
    
        ruleForm: {
    
    
          name: '',
          region: '',
          date1: '',
          date2: '',
          delivery: false,
          type: [],
          resource: '',
          desc: ''
        },
        rules: {
    
    
          name: [
            {
    
     required: true, message: '请输入活动名称', trigger: 'blur' },
            {
    
     min: 3, max: 5, message: '长度在 35 个字符', trigger: 'blur' }
          ],
          region: [
            {
    
     required: true, message: '请选择活动区域', trigger: 'change' }
          ],
          date1: [
            {
    
     type: 'date', required: true, message: '请选择日期', trigger: 'change' }
          ],
          date2: [
            {
    
     type: 'date', required: true, message: '请选择时间', trigger: 'change' }
          ],
          type: [
            {
    
     type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change' }
          ],
          resource: [
            {
    
     required: true, message: '请选择活动资源', trigger: 'change' }
          ],
          desc: [
            {
    
     required: true, message: '请填写活动形式', 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. Single form field form validation

  Applicable to fields that require individual verification, or verification of form fields with changes.
  The sample code is as follows:

<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px" class="demo-dynamic">
  <el-form-item
    prop="email"
    label="邮箱"
    :rules="[
      {
    
     required: true, message: '请输入邮箱地址', trigger: 'blur' },
      {
    
     type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ]"
  >
    <el-input v-model="dynamicValidateForm.email"></el-input>
  </el-form-item>
  <el-form-item
    v-for="(domain, index) in dynamicValidateForm.domains"
    :label="'域名' + index"
    :key="domain.key"
    :prop="'domains.' + index + '.value'"
    :rules="{
    
    
      required: true, message: '域名不能为空', trigger: 'blur'
    }"
  >
    <el-input v-model="domain.value"></el-input><el-button @click.prevent="removeDomain(domain)">删除</el-button>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button>
    <el-button @click="addDomain">新增域名</el-button>
    <el-button @click="resetForm('dynamicValidateForm')">重置</el-button>
  </el-form-item>
</el-form>
<script>
  export default {
    
    
    data() {
    
    
      return {
    
    
        dynamicValidateForm: {
    
    
          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(item) {
    
    
        var index = this.dynamicValidateForm.domains.indexOf(item)
        if (index !== -1) {
    
    
          this.dynamicValidateForm.domains.splice(index, 1)
        }
      },
      addDomain() {
    
    
        this.dynamicValidateForm.domains.push({
    
    
          value: '',
          key: Date.now()
        });
      }
    }
  }
</script>

3. Custom validation rules

  Applicable to the situation where the definition rules in Elment-UI cannot meet the requirements and you need to define the validation rules yourself.
You need to add custom validation rules in data() {}, and then refer to the validation rules through the validator in the return of data. The rules defined in data() {return{}} must have the same value of the :rules attribute, and the object userName in the rules must have the same value as the prop attribute in and.
The sample code is as follows:

<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>
<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: [
            {
    
     validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            {
    
     validator: validatePass2, trigger: 'blur' }
          ],
          age: [
            {
    
     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>

  There are two writing positions for custom rules:

  1. Write rules in data, the sample code is as follows:


data() {
    
    
    // 自定义校验规则
    var bargainMoney = (rule, value, callback) => {
    
    
      // rule 对应使用bargainMoney自定义验证的 对象
      // value 对应使用bargainMoney自定义验证的 数值 
      // callback 回调函数
      const r = /^+?[1-9][0-9]*$/; // 正整数
      if (value == null || String(value).trim() === "") {
    
    
        callback(new Error("不能为空"));
      } else if (!r.test(value)) {
    
    
        callback(new Error("请输入正整数"));
      }else {
    
    
        callback();
      }
    };
   return {
    
    
      formData: {
    
    
        haggleNumber: "", // 砍价人数
      },
      rules: {
    
    
        haggleNumber: [
          {
    
    
            required: true,
            validator: bargainMoney,
            trigger: "blur"
          }
        ],
      }
   }
}
  1. Write rules in methods, the sample code is as follows:
data() {
    
    
 return {
    
    
      formData: {
    
    
        haggleNumber: "", // 砍价人数
      },
      rules: {
    
    
        haggleNumber: [
          {
    
    
            required: true,
            validator: this.bargainMoney,
            trigger: "blur"
          }
        ]
      }
 }
},
methods: {
    
    
    // 自定义校验规则
    bargainMoney(rule, value, callback){
    
    
      // rule 对应使用bargainMoney自定义验证的 对象
      // value 对应使用bargainMoney自定义验证的 数值 
      // callback 回调函数
      const r = /^+?[1-9][0-9]*$/; // 正整数
      if (value == null || String(value).trim() === "") {
    
    
        return callback(new Error("不能为空"));
      } else if (!r.test(value)) {
    
    
        return callback(new Error("请输入正整数"));
      }else {
    
    
        return callback();
      }
    }
}

The difference between the two is:

  1. There is no need to pass the return callback function in data, but it is required in methods.
  2. The verification rules written in methods need to be obtained through this when configuring rules in rules.

4. Dynamically increase or decrease form items

  In addition to passing all validation rules on the Form component at once, you can also pass attribute validation rules on a single form field.
  The sample code is as follows:

<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px" class="demo-dynamic">
  <el-form-item
    prop="email"
    label="邮箱"
    :rules="[
      {
    
     required: true, message: '请输入邮箱地址', trigger: 'blur' },
      {
    
     type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ]"
  >
    <el-input v-model="dynamicValidateForm.email"></el-input>
  </el-form-item>
  <el-form-item
    v-for="(domain, index) in dynamicValidateForm.domains"
    :label="'域名' + index"
    :key="domain.key"
    :prop="'domains.' + index + '.value'"
    :rules="{
    
    
      required: true, message: '域名不能为空', trigger: 'blur'
    }"
  >
    <el-input v-model="domain.value"></el-input><el-button @click.prevent="removeDomain(domain)">删除</el-button>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button>
    <el-button @click="addDomain">新增域名</el-button>
    <el-button @click="resetForm('dynamicValidateForm')">重置</el-button>
  </el-form-item>
</el-form>
<script>
  export default {
    
    
    data() {
    
    
      return {
    
    
        dynamicValidateForm: {
    
    
          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(item) {
    
    
        var index = this.dynamicValidateForm.domains.indexOf(item)
        if (index !== -1) {
    
    
          this.dynamicValidateForm.domains.splice(index, 1)
        }
      },
      addDomain() {
    
    
        this.dynamicValidateForm.domains.push({
    
    
          value: '',
          key: Date.now()
        });
      }
    }
  }
</script>

Guess you like

Origin blog.csdn.net/yanghang1122/article/details/125585278