vue element-ui的form表单校验总结,动态校验、自

2021-08-03  本文已影响0人  家乡_a6ce

写了一段时间的vue,前端用了element-ui,经常会用到from表单,总结一下form表单的校验,以及遇到过的问题。

1、正常添加校验流程,在form表单加rule
2、只想对单个input校验
3、自定义校验(例如用正则校验手机号码、数字、url、中文等)
4、添加动态校验(可以根据需要显示校验或者改变校验规则)
5、遇到校验无效的问题

一:正常添加校验流程,在form表单加rule

1、在el-form里面添加:rules=“rules”
2、在el-form-item里面添加prop,prop对应:model="form"的form的属性
3、然后在data里面添加属性rules
4、在点击提交的按钮里面validate的校验

<el-form :model="form" :rules="rules" ref="form">
            <el-form-item label="用户名称:" prop="username">
                <el-input v-model="form.username"  clearable :disabled="true"></el-input>
            </el-form-item>
            .....
</el-form>
data() {
    return {
      //在rules属性填写相关字段的校验规则
      rules: {
        username: [
            { required: true, message: "必填" },
            { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        email:[{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'change' }],
  
      }
   }
}
methods: {
      onSubmit() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            //调用接口保存
          } else {
              this.$message.error('请完善表单相关信息!');
            return false;
          }
        });

      },
      //或者
      onSubmit() {
         if(!this.checkForm()){
           this.$message.error('请完善表单相关信息!');
           return;
         }
         //调用接口保存

      },
      // 表单校验
     checkForm(){
       // 1.校验必填项
       let validForm = false;
       this.$refs.form.validate(valid => {validForm = valid})
       if(!validForm){
         return false;
       }
       //其他的校验
       /*if(){
          return false;
       }*/
       return true;
     }
      
}
二:对单个input校验

有时候并不想在form增加rules校验,只想对单个input增加校验,直接在el-form-item里面加rules

<el-form-item label="开始日期" :rules="{
      required: true, message: '开始日期不能为空', trigger: 'blur' }">
              <el-date-picker  v-model="form.startTime" type="date" placeholder="开始日期">
                <i slot="suffix" class="el-input__icon el-icon-date"></i>
              </el-date-picker>
</el-form-item>
三:自定义校验(正则校验手机号码、数字、url、中文)

提供几个用正则表达式做的自定义校验规则demo

data() {
    return {
      //在rules属性填写相关字段的校验规则
      rules: {
        username: [
            { required: true, message: "必填" },
            { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        email:[{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'change' }],
        //自定义校验
        name:[
            { required: true, message: '请输入姓名', trigger: 'blur' },
            { validator:function(rule,value,callback){
                          //校验中文的正则:/^[\u4e00-\u9fa5]{0,}$/
                          if(/^[\u4e00-\u9fa5]{0,}$/.test(value) == false){
                              callback(new Error("请输入中文"));
                          }else{
                              //校验通过
                              callback();
                          }
                        }, trigger: 'blur'
             },
        ],
        phone:[
               { required: true, message: '请输入手机号码', trigger: 'blur' },
               { validator:function(rule,value,callback){
                            if(/^1[34578]\d{9}$/.test(value) == false){
                                   callback(new Error("请输入正确的手机号"));
                            }else{
                                   callback();
                            }
                          }, trigger: 'blur'
                },
        ],
        age:[
              { validator:function(rule,value,callback){
                               if(/^[0-9]*$/.test(value) == false){
                                   callback(new Error("请输入正确的数字"));
                               }else{
                                   callback();
                               }
                           }, trigger: 'blur'
              },
        ],
        url:[
             { validator:function(rule,value,callback){
                               if(/^http:\/\/([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?$/.test(value) == false){
                                   callback(new Error("请输入正确的Url"));
                               }else{
                                   callback();
                               }
                           }, trigger: 'blur'
             },
        ],
      }
   }
}
四:添加动态校验(可以根据需要显示校验或者改变校验规则)

遇到过一种,根据form表单的一个下拉列表的选项来判断某些字段是否校验,选了A,要校验几个字段必填,选了B又要校验其他几个字段必填,这时候表单的校验需要动态添加,这时候我们需要动态改变rules属性相关的校验即可

例如刚刚这种根据下拉列表的选项来动态触发校验的,那么在el-select里面加@change事件,每次下拉列表改变就触发事件来改变form表单的校验规则

<el-select v-model="value" placeholder="请选择" @change="resetValidate">
data() {
    return {
      //在rules属性填写相关字段的校验规则
      rules: {
        phone: [{ required: true, message: "必填" }],
        email:[{ required: true, message: "必填" }],
  
      }
   }
},
methods: {
    //改变状态时动态重置校验规则
    resetValidate(){
      if(this.form.status== 1){
         //重置rules的phone、email的属性值,只校验手机,不校验邮箱
        this.rules.phone= [{ required: true, message: "必填" }];
        this.rules.email= [];
      }else{
        //只校验邮箱,不校验手机
        this.rules.phone= [];
        this.rules.email= [{ required: true, message: "必填" }];
      }
      this.$refs.form.clearValidate();
    },
}
五:validator用法

validator验证器,可以对格式进行复杂限制,
跟rule一样需要设置对应表单项的prop属性,然后绑定validator,validator绑定验证规则变量(注意验证规则变量是处在data的return外面)。

data() {
    //rule表示要验证的规则,value表示输入值,callback回调
    var checkEmail = (rule, value, callback) => {
      let mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (!value) { //如果输入为空直接返回
        callback();
      } else {
        //如果字符串 string 中含有与 RegExpObject 匹配的文本,则返回 true,否则返回 false。
        if (mailReg.test(value)) {  //匹配成功返回
          callback();   
        } else {    //匹配不成功返回错误显示
          callback(new Error("邮箱格式:xx@xx.xx,只含数字、大小写字母、下划线、横杠"));
        }
      }
    };
    var checkPhone = (rule,value,callback) =>{
      let phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
      if(!value){
        callback()
      }else{
        if(phoneReg.test(value)){
          callback()
        }else{
          callback(new Error("电话格式:13、14、15、17、18开头+9位阿拉伯数字"))
        }
      }
    }
    return {
      isEdit: false,
      user: {},
      tempUser: {},
      rules: {
        userName: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        account: [
          // { required: true, message: "请输入账户", trigger: "blur" },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        userEmail: [
          { validator: checkEmail, trigger: "blur" },
        ],
        phone: [
          { validator: checkPhone,trigger: "blur" },
        ],
      },
    };
  },

在方法中判断验证器是否全部通过:

// valid在全部validator通过才会返回true,否则为false
this.$refs.userForm.validate((valid) => {
        if (!valid) {
          this.message("warning", "请修改正确的数据格式!");
          return;
        } else {
          //验证通过调用保存接口
        }

六:遇到校验无效的问题

有一次遇到一个校验无效的问题,from表单其他字段校验都有效,就是有一个el-date-picker的校验一直没有效果,检查发现在el-form-item里面添加prop,prop对应:model="form"的form的属性并不是当前form里面的属性值.,所以这个el-date-picker没有触发校验

<el-form :model="form" :rules="rules" ref="form">
            <el-form-item label="用户名称:" prop="username">
                <el-input v-model="form.username"  clearable :disabled="true"></el-input>
            </el-form-item>
            .....
</el-form>
// 1.里面的el-input绑定的username必须是:model="form"的form里面的属性
// 2.并且el-form-item的prop=username,才会校验生效,否则在element-ui会没有校验效果
七:案例
<el-form
          ref="formInline"
          :model="formInline"
          :rules="ruleInline"
          class=""
          :label-position="labelPosition"
          label-width="120px"
        >
          <div class="f-r-fs-1">
            <div class="formItem">
              <el-form-item prop="trackNo" label="快递单号:" style="width: 280px">
                <el-input
                  v-model="formInline.trackNo"
                  placeholder="请输入快递单号"
                  style="width: 150px"
                  :disabled="trackNoD"
                  size="small"
                  @input="changeHandle"
                />
              </el-form-item>
            </div>
            <div class="formItem" style="width: 280px">
              <el-form-item label="运单号:" prop="transportOrderCode">
                <el-input
                  v-model="formInline.transportOrderCode"
                  placeholder="请输入运单号"
                  style="width: 150px"
                  :disabled="showHidden"
                  size="small"
                />
              </el-form-item>
            </div>
            <div class="formItem" style="width: 280px">
              <el-form-item label="赔付类型:" prop="claimTypeId">
                <el-select
                  ref="refType"
                  v-model="formInline.claimTypeId"
                  clearable
                  style="width: 150px"
                  size="small"
                  placeholder="请选择赔付类型"
                  :disabled="showHidden"
                  @change="selectType"
                >
                  <el-option
                    v-for="item in compentType"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div>
          <div class="f-r-fs-1">
            <div class="formItem">
              <el-form-item label="收件人:" style="width: 280px">
                <el-input
                  v-model="formInline.receiveName"
                  maxlength="30"
                  placeholder="请输入收件人"
                  style="width: 150px"
                  :disabled="showHidden"
                  size="small"
                />
              </el-form-item>
            </div>
            <div class="formItem">
              <el-form-item label="收件人手机:" style="width: 280px" prop="receiveMobile">
                <el-input
                  v-model="formInline.receiveMobile"
                  placeholder="请输入收件人手机"
                  style="width: 150px"
                  :disabled="showHidden"
                  size="small"
                />
              </el-form-item>
            </div>
            <div class="formItem">
              <el-form-item label="收件地址:" style="width: 280px">
                <el-input
                  v-model="formInline.receiveAddr"
                  maxlength="255"
                  placeholder="请输入收件地址"
                  style="width: 150px"
                  :disabled="showHidden"
                  size="small"
                />
              </el-form-item>
            </div>
          </div>
          <div class="f-r-fs-1">
            <div class="formItem">
              <el-form-item label="所在区县:" style="width: 280px" prop="areaId">
                <el-cascader
                  ref="unitAreacode"
                  v-model="formInline.areaId"
                  expand-trigger="hover"
                  filterable
                  props-check-strictly="true"
                  clearable
                  size="small"
                  placeholder="请选择省份-请选择城市-请选择区县"
                  :options="area"
                  :props="{ value: 'areaId',label:'areaName', children:'subs'}"
                  style="width: 150px"
                  :disabled="showHidden"
                  @change="handleChange"
                />
              </el-form-item>
            </div>
            <div class="formItem">
              <el-form-item label="快递商:" style="width: 280px">
                <el-select
                  v-model="formInline.supplierCode"
                  clearable
                  style="width: 150px"
                  size="small"
                  :disabled="showHidden"
                  placeholder="请选择快递商"
                >
                  <el-option
                    v-for="item in supplier"
                    :key="item.supplierCode"
                    :label="item.supplierName"
                    :value="item.supplierCode"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div>
          <div class="f-r-fs-1">
            <div class="formItem" style="width: 280px">
              <el-form-item prop="claimName" label="责任人:">
                <el-input
                  v-model="formInline.claimName"
                  placeholder="请输入责任人"
                  style="width: 150px"
                  :disabled="showHidden"
                  size="small"
                />
              </el-form-item>
            </div>
            <div class="formItem" style="width: 280px" prop="claimMoney">
              <el-form-item prop="claimMoney" label="赔付金额:">
                <el-input
                  v-model="formInline.claimMoney"
                  placeholder="请输入赔付金额"
                  style="width: 150px"
                  :disabled="showHidden"
                  size="small"
                  @input="testinput"
                />
              </el-form-item>
            </div>
            <div class="formItem" style="width: 280px">
              <el-form-item prop="receiverName" label="赔付对象:">
                <el-input
                  v-model="formInline.receiverName"
                  placeholder="请输入赔付对象"
                  style="width: 150px"
                  :disabled="showHidden"
                  size="small"
                />
              </el-form-item>
            </div>
          </div>
          <div class="f-r-fs-1">
            <div class="formItem" style="width: 280px">
              <el-form-item prop="remark" label="问题描述:">
                <el-input
                  v-model="formInline.remark"
                  type="textarea"
                  :autosize="{minRows:5,maxRows:10}"
                  placeholder="请输入问题描述"
                  style="width: 300px"
                  :disabled="showHidden"
                />
              </el-form-item>
            </div>
          </div>
          <div class="f-r-fs-1">
            <div class="formItem" style="width: 280px">
              <el-form-item label="赔付依据:" prop="claimEvidence">
                <el-input
                  v-model="formInline.claimEvidence"
                  type="textarea"
                  :autosize="{minRows: 5,maxRows:10}"
                  placeholder="请输入赔付依据"
                  style="width: 300px"
                  :disabled="showHidden"
                  size="small"
                />
              </el-form-item>
            </div>
          </div>
          <div class="f-r-fs-1">
            <div class="formItem">
              <el-form-item prop="uploadList" label="预览图片:" style="">
                <!--                  :file-list="formInline.claimPics"-->
                <!--                :file-list="formInline.claimPics"-->
                <el-upload
                  class="upload"
                  :class="{hide:hideUploadEdit}"
                  :disabled="showHidden"
                  action="#"
                  :auto-upload="false"
                  list-type="picture-card"
                  multiple
                  :limit="9"
                  :file-list="formInline.fileList"
                  :headers="importHeaders"
                  :accept="acceptFileType"
                  :on-change="onChangeFj"
                  :on-exceed="handleExceed"
                  :on-preview="handlePreview"
                  :before-remove="beforeRemove"
                  :on-remove="handleRemove"
                  :before-upload="beforeAvatarUpload"
                >
                  <i class="el-icon-plus" style="font-size: 28px"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible" size="tiny" append-to-body>
                  <img width="100%" height="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
              </el-form-item>
            </div>
          </div>
          <div class="f-r-fs-1">
            <div class="formItem" style="width: 280px">
              <el-form-item label="赔付状态:">
                <el-select
                  ref="refStatus"
                  v-model="formInline.claimStatus"
                  clearable
                  style="width: 150px"
                  size="small"
                  :disabled="showHidden"
                  placeholder="请输入赔付状态"
                  @change="changeSelect"
                >
                  <!--                  <el-option value="0" label="定责中" />-->
                  <!--                  <el-option value="1" label="驳回定责" />-->
                  <!--                  <el-option value="2" label="确认赔付" />-->
                  <el-option
                    v-for="item in claimStatusList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div>
        </el-form>
ruleInline : {
        claimTypeId: [{ required: true, message: '赔付类型必选', trigger: 'change' }],
        trackNo: [{ required: true, message: '订单号必填', trigger: 'blur' }],
        areaId: [{ type: 'array', required: true, message: '所在区县必填', trigger: 'change' }],
        receiveMobile: [{ validator: Format.FormValidate.Form().Tels, trigger: 'blur' }],
        claimMoney: [{ validator: Format.FormValidate.Form().moneyAmount, required: true, trigger: 'blur' }],

        claimName: [],
        receiverName: [],
        claimEvidence: [],
        remark: []
        // claimName: [{ required: true, message: '责任人必填', trigger: 'blur' }],
        // receiverName: [{ required: true, message: '赔付对象必填', trigger: 'blur' }],
        // claimEvidence: [{ required: true, message: '赔付依据必填', trigger: 'blur' }],
        // remark: [{ required: true, message: '问题描述必填', trigger: 'blur' }]
      }
 // 赔付类型
    changeSelect(e) {
      this.claimStatusName = this.$refs.refStatus.$slots.default[e].child.label
      if (e === '2') {
        this.ruleInline.claimTypeId = [{ required: true, message: '赔付类型必选', trigger: 'change' }],
        this.ruleInline.trackNo = [{ required: true, message: '订单号必填', trigger: 'blur' }],
        this.ruleInline.areaId = [{ type: 'array', required: true, message: '所在区县必填', trigger: 'change' }],
        this.ruleInline.receiveMobile = [{ validator: Format.FormValidate.Form().Tels, trigger: 'blur' }],
        this.ruleInline.claimMoney =  [{ validator: Format.FormValidate.Form().money, required: true, trigger: 'blur' }],
        this.ruleInline.claimName = [{ required: true, message: '责任人必填', trigger: 'blur' }],
        this.ruleInline.receiverName =  [{ required: true, message: '赔付对象必填', trigger: 'blur' }],
        this.ruleInline.claimEvidence = [{ required: true, message: '赔付依据必填', trigger: 'blur' }],
        this.ruleInline.remark =[{ required: true, message: '问题描述必填', trigger: 'blur' }]
        // this.ruleInline = {
        //   claimTypeId: [{ required: true, message: '赔付类型必选', trigger: 'change' }],
        //   trackNo: [{ required: true, message: '订单号必填', trigger: 'blur' }],
        //   areaId: [{ type: 'array', required: true, message: '所在区县必填', trigger: 'change' }],
        //   receiveMobile: [{ validator: Format.FormValidate.Form().Tels, trigger: 'blur' }],
        //   claimMoney: [{ validator: Format.FormValidate.Form().money, required: true, trigger: 'blur' }],
        //
        //   claimName: [{ required: true, message: '责任人必填', trigger: 'blur' }],
        //   receiverName: [{ required: true, message: '赔付对象必填', trigger: 'blur' }],
        //   claimEvidence: [{ required: true, message: '赔付依据必填', trigger: 'blur' }],
        //   remark: [{ required: true, message: '问题描述必填', trigger: 'blur' }]
        // }
      } else {
        this.ruleInline.claimName = []
        this.ruleInline.claimMoney = []
        this.ruleInline.receiverName = []
        this.ruleInline.claimEvidence = []
        this.ruleInline.remark = []
      }
      this.$refs.formInline.clearValidate()
    },

案例二:

 data() {
    const vm = this
    var checkMoney = (rule, value, callback) => {
      debugger
      if (value >= vm.formInline.deductionAmount) {
        callback(new Error('应追回金额小于等于赔付金额'))
      } else {
        // 校验通过
        callback()
      }
    }
    return {
      // 退款状态
      refundedStatusType: [
        {
          code: 'YZH',
          name: '已追回'
        }, {
          code: 'DZH',
          name: '待追回'
        }
      ],
      // 对其方式
      labelPosition: 'right',
      // 定义一个IsShow来接收传递过来的值
      IsShow: this.modal,
      formInline: {
        fkClaimId: null,
        // 主键Id
        pkCancelClaimId: null,
        // 运单号
        trackNo: null,
        // 快递商
        supplierCode: null,
        // 责任人
        personLiable: null,
        // 已赔付金额
        claimAmount: null,
        deductionAmount: null,
        // 待退款金额
        beforeRefundedAmount: null,
        // 退款金额
        refundedAmount: null,
        // 撤销原因
        cancelReason: null,
        // 退款状态
        refundedStatus: null
      },
      ruleInline: {
        refundedStatus: [{ required: true, message: '追回状态必选', trigger: 'change' }],
        cancelReason: [{ required: true, message: '撤销原因必填', trigger: 'blur' }],
        // deductionAmount 赔付金额 追回金额,必须必赔付金额小或等于
        beforeRefundedAmount: [
          { required: true, message: '应追回金额必填', trigger: 'blur' },
          { validator: checkMoney, trigger: 'blur' }
          /*     { validator: function(rule, value, callback) {
            debugger
            console.log(rule, value)
            // 校验中文的正则:/^[\u4e00-\u9fa5]{0,}$/
            console.log(this.formInline.beforeRefundedAmount)
            console.log(this.formInline.deductionAmount)
            if (value <= this.formInline.deductionAmount) {
              callback(new Error('应追回金额应该小于等于赔付金额'))
            } else {
              // 校验通过
              callback()
            }
          }, trigger: 'blur'
          }*/
        ],
        refundedAmount: [{ required: true, message: '应退款金额必填', trigger: 'blur' }]
      }
    }
  },
const vm = this
    var checkMoney = (rule, value, callback) => {
      debugger
      if (value <= vm.formInline.deductionAmount) {
        // 校验通过
        callback()
      } else {
        callback(new Error('应追回金额小于等于赔付金额'))
      }
    }
    var refundedMoney = (rule, value, callback) => {
      debugger
      if (value <= vm.formInline.beforeRefundedAmount) {
        // 校验通过
        callback()
      } else {
        callback(new Error('追回金额小于等于应追回金额'))
      }
    }
 ruleInline: {
        refundedStatus: [{ required: true, message: '追回状态必选', trigger: 'change' }],
        cancelReason: [{ required: true, message: '撤销原因必填', trigger: 'blur' }],
        // deductionAmount 赔付金额 追回金额,必须必赔付金额小或等于
        beforeRefundedAmount: [
          { required: true, message: '应追回金额必填', trigger: 'blur' },
          { validator: checkMoney, trigger: 'blur' }
        ],
        refundedAmount: [{ required: true, message: '应退款金额必填', trigger: 'blur' },
          { validator: refundedMoney, trigger: 'blur' }]
      }
上一篇下一篇

猜你喜欢

热点阅读