Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

1. Forms of Form verification in Element-UI

1.1 Basic/Custom

Rules are bound to el-Form, rLUES are verification rules, and corresponding prop is bound to El-Form-Item.

Custom rule validator: checkAge function for custom rules.

Elem. IO /#/ zh-cn /com… .

<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
    <el-form-item label="Activity Name" prop="name">
      <el-input v-model="ruleForm.name"></el-input>
    </el-form-item>
    <el-form-item label="Age" prop="age">
      <el-input v-model.number="ruleForm.age"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">Immediately create</el-button>
      <el-button @click="resetForm('ruleForm')">reset</el-button>
    </el-form-item>
  </el-form>  
</template>

<script>
var checkAge = (rule, value, callback) = > {
  if(! value) {return callback(new Error('Age cannot be empty'));
  }
  if (!Number.isInteger(value)) {
    callback(new Error('Please enter a numeric value'));
  } else {
    if (value < rule.max_age) {
      callback(new Error('Must be at least 18 years old'));
    } else{ callback(); }}};export default {
  data() {
    return {
      ruleForm: {
        name: ' '.age:' '
      },
      rules: {
        name: [{required: true.message: 'Please enter an activity name'.trigger: 'blur' },
          { min: 3.max: 5.message: 'Between 3 and 5 characters long'.trigger: 'blur'}].age: [{max_age:18.validator: checkAge, trigger: 'blur' }// checkAge custom rule function]}}; },methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) = > {
        if (valid) {
          alert('submit! ');
        } else {
          console.log('error submit!! ')}}); },resetForm(formName) {
      this.$refs[formName].resetFields(); }}}</script>
Copy the code

1.2 Inter-line verification

<el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px">
  <el-form-item
    label="Age"
    prop="age"
    :rules="[{required: true, message: 'Age cannot be empty '}, {type: 'number', message:' Age must be a numeric value '}]">
    <el-input type="age" v-model.number="numberValidateForm.age" autocomplete="off"></el-input>
  </el-form-item>
</el-form>  
Copy the code

1.4 User-defined inter-line verification

<template>
  <el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px">
    <el-form-item
      label="Age"
      prop="age"
      :rules="[ {max_age:18, validator: checkAge, trigger: 'blur' } ]">
      <el-input type="age" v-model.number="numberValidateForm.age" autocomplete="off"></el-input>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return{}},methods: {
    checkAge(rule, value, callback){
      if(! value) {return callback(new Error('Age cannot be empty'));
      }
      if (!Number.isInteger(value)) {
        callback(new Error('Please enter a numeric value'));
      } else {
        if (value < rule.max_age) {
          callback(new Error('Must be at least 18 years old'));
        } else{ callback(); }}},}}</script>
Copy the code

1.5 Inter-line loop custom verification

${index}. Value =” Domains.${index}. Value “;

<template>
  <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px">
    <el-form-item
      v-for="(item, index) in dynamicValidateForm.domains"
      :key="item.index"
      :label='domain name' + index '
      :prop="`domains.${index}.value`"
      :rules="[{required: true, message: 'Domain name cannot be empty ', trigger: 'blur'}, {reg:/^--------$/, validator: checkDomain, trigger: 'blur' } ]">
      <el-input v-model="item.value" placeholder="Please enter the content"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('dynamicValidateForm')">submit</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      dynamicValidateForm: {
        domains: [{value: ' '},
          { value: ' '},
          { value: ' '}]}}; },methods: {
    checkDomain(rule, value, callback){
      // Customize the verification rule
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) = > {
        if (valid) {
          alert('submit! ');
        } else {
          console.log('error submit!! '); }}); }}}</script>
Copy the code

2. Comprehensive cases

In this case, the element-UI form has a nested table, and each cell in the table can input, select, upload files, etc., as well as verify the rules of the entire form.

<template>
  <div>
    <el-button type="primary" size="mini" @click="saveTableForm('tableForm')">save</el-button>
    <el-form
      :model="tableForm"
      ref="tableForm">
      <el-table
        :data="tableForm.tableData"
        border
        stripe>
        <el-table-column label="Province" prop="province"></el-table-column>
        <el-table-column label="City">
          <template slot-scope="scope">
            <el-form-item
              label=""
              label-width="12px"
              :prop="'tableData.' + scope.$index + '.city'"
              :rules="tableDataRules.city">
              <el-select size="mini" v-model="scope.row.city" placeholder="Please select" clearable>
                <el-option
                  v-for="item in scope.row.cityOPtions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="Operator">
          <template slot-scope="scope">
            <el-form-item
              label=""
              label-width="12px"
              :prop="'tableData.' + scope.$index + '.name'"
              :rules="tableDataRules.name">
              <el-input v-model="scope.row.name" placeholder="Operator" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="File">
          <template slot-scope="scope">
            <el-form-item
              label=""
              label-width="12px"
              :prop="'tableData.' + scope.$index + '.file'"
              :rules="tableDataRules.file">
              <! Add an index parameter to the component's callback function
              <el-upload
                multiple
                action="https://jsonplaceholder.typicode.com/posts/"
                :on-progress="function(event,file,fileList){ return handleUploadProgress(event,file,fileList)}"
                :on-remove="function(file,fileList){ return handleUploadRemove(file,fileList,scope.$index)}"
                :on-success="function(res,file,fileList){ return handleUploadSuccess(res,file,fileList,scope.$index)}"
                :file-list="uploadFileList[scope.$index]">
                <el-button type="text">Upload a file</el-button>
              </el-upload>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableForm: {
        tableData: [{province: "Hubei".city: "".cityOPtions:[
              {label: 'Wuhan'.value:'Wuhan'},
              {label: 'Yichang'.value:'Yichang'}].name: "".file:' '}, {province: "Chongqing".city: "".cityOPtions:[
              {label: 'Yubei District'.value:'Yubei District'},
              {label: 'Kowloon Po District'.value:'Kowloon Po District'}].name: "".file:' ',}]},tableDataRules: {
        name: [{required: true.message: "Please enter your name".trigger: "blur"},].city: [{required: true.message: "Please select a city".trigger: "change"},].file: [{required: true.message: "Please upload file".trigger: "change"},],},uploadFileList: [[]],// Upload file list
    };
    
  },
  methods: {
    / / save
    saveTableForm(formName) {
      this.$refs[formName].validate((valid) = > {
        if (valid) {
           console.log('Check pass'.this.tableForm,this.uploadFileList)
        }
      });
    }, 
    // Preview the image
    handleUploadProgress(event,file,fileList) {},
    // Delete the image
    handleUploadRemove(file, fileList, index) {
      this.tableForm.tableData[index].file = ' ';
      this.uploadFileList[index] = fileList;
    },
    // File upload
    handleUploadSuccess(res, file, fileList, index) {
      this.tableForm.tableData[index].file = res.id;
      // After upload, assign the returned fileList to the fileList of the corresponding component
      this.uploadFileList[index] = fileList; }}};</script>
Copy the code