當(dāng)前位置:首頁 > IT技術(shù) > Web編程 > 正文

Element-ui中 表單(Form)校驗的幾種形式 及 表單嵌套表格含上傳(Upload)組件的
2021-10-21 23:07:41

1. Element-ui中 表單(Form)校驗的幾種形式

1.1 基礎(chǔ) / 自定義

在 el-form 上綁定 rules,rlues為校驗規(guī)則,在 el-form-item 上綁定對應(yīng)的prop;
自定義規(guī)則,validator:checkAge,自定義規(guī)則的函數(shù)。
詳細(xì)的可查看 element 文檔 http://element-cn.eleme.io/#/zh-CN/component/form。

<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
    <el-form-item label="活動名稱" prop="name">
      <el-input v-model="ruleForm.name"></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')">立即創(chuàng)建</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>  
</template>

<script>
var checkAge = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('年齡不能為空'));
  }
  if (!Number.isInteger(value)) {
    callback(new Error('請輸入數(shù)字值'));
  } else {
    if (value < rule.max_age) {
      callback(new Error('必須年滿18歲'));
    } else {
      callback();
    }
  }
};

export default {
  data() {
    return {
      ruleForm: {
        name: '',
        age:''
      },
      rules: {
        name: [
          { required: true, message: '請輸入活動名稱', trigger: 'blur' },
          { min: 3, max: 5, message: '長度在 3 到 5 個字符', trigger: 'blur' }
        ],
        age: [
          {max_age:18, validator: checkAge, trigger: 'blur' }// checkAge自定義規(guī)則函數(shù)
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!');
        } else {
          console.log('error submit!!')
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

1.2 行間校驗

<el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px">
  <el-form-item
    label="年齡"
    prop="age"
    :rules="[
      { required: true, message: '年齡不能為空'},
      { type: 'number', message: '年齡必須為數(shù)字值'}
    ]">
    <el-input type="age" v-model.number="numberValidateForm.age" autocomplete="off"></el-input>
  </el-form-item>
</el-form>  

1.4 行間自定義校驗

<template>
  <el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px">
    <el-form-item
      label="年齡"
      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('年齡不能為空'));
      }
      if (!Number.isInteger(value)) {
        callback(new Error('請輸入數(shù)字值'));
      } else {
        if (value < rule.max_age) {
          callback(new Error('必須年滿18歲'));
        } else {
          callback();
        }
      }
    },
  }
}
</script>

1.5 行間循環(huán)自定義校驗

關(guān)鍵代碼 :prop="domains.${index}.value",這是 Element-ui 規(guī)定的格式,渲染后的結(jié)果為:domains.1.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="'域名' + index"
      :prop="`domains.${index}.value`"
      :rules="[
        { required: true, message: '域名不能為空', trigger: 'blur' },
        { reg:/^--------$/, validator: checkDomain, trigger: 'blur' }
      ]">
      <el-input v-model="item.value" placeholder="請輸入內(nèi)容"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      dynamicValidateForm: {
        domains: [
          { value: ''},
          { value: ''},
          { value: ''},
        ]
      }
    };
  },
  methods: {
    checkDomain(rule, value, callback){
      //自定義校驗規(guī)則
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!');
        } else {
          console.log('error submit!!');
        }
      });
    }
  }
}
</script>

2. 綜合應(yīng)用

案例中, Element-ui 表單里嵌套了表格,表格內(nèi)每個單元格都能進(jìn)行表單控件的輸入、選擇、上傳文件等操作,同時能針對整個表單的規(guī)則進(jìn)行校驗。

在這里插入圖片描述

<template>
  <div>
    <el-button type="primary" size="mini" @click="saveTableForm('tableForm')">保存</el-button>
    <el-form
      :model="tableForm"
      ref="tableForm">
      <el-table
        :data="tableForm.tableData"
        border
        stripe>
        <el-table-column label="省份" prop="province"></el-table-column>
        <el-table-column label="城市">
          <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="請選擇" 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="操作人">
          <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="操作人" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="文件">
          <template slot-scope="scope">
            <el-form-item
              label=" "
              label-width="12px"
              :prop="'tableData.' + scope.$index + '.file'"
              :rules="tableDataRules.file">
              <!-- 在組件的回調(diào)函數(shù)里加一個索引的參數(shù) -->
              <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">上傳文件</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: "湖北",
            city: "",
            cityOPtions:[
              {label: '武漢市',value:'武漢市'},
              {label: '宜昌市',value:'宜昌市'}
            ],
            name: "",
            file:'',
          },{
            province: "重慶",
            city: "",
            cityOPtions:[
              {label: '渝北區(qū)',value:'渝北區(qū)'},
              {label: '九龍坡區(qū)',value:'九龍坡區(qū)'}
            ],
            name: "",
            file:'',
          },
        ],
      },
      tableDataRules: {
        name: [
          { required: true, message: "請輸入姓名", trigger: "blur" },
        ],
        city: [
          { required: true, message: "請選擇城市", trigger: "change" },
        ],        
        file: [
          { required: true, message: "請上傳文件", trigger: "change" },
        ],
      },
      uploadFileList:[[]], // 上傳文件列表
    };

  },
  methods: {
    // 保存
    saveTableForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('校驗通過',this.tableForm,this.uploadFileList)
        }
      });
    }, 
    // 預(yù)覽圖片
    handleUploadProgress(event,file,fileList) {},
    // 刪除圖片
    handleUploadRemove(file, fileList, index) {
      this.tableForm.tableData[index].file = '';
      this.uploadFileList[index] = fileList;
    },
    // 文件上傳
    handleUploadSuccess(res, file, fileList, index) {
      this.tableForm.tableData[index].file = res.id;
      // 上傳之后,把返回的fileList賦值給對應(yīng)組件的fileList
      this.uploadFileList[index] = fileList;
    }
  },
};
</script>

本文摘自 :https://blog.51cto.com/u

開通會員,享受整站包年服務(wù)立即開通 >