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

案例1

当不选择非长期营业期限时,不需要校验营业期限字段;当选择非长期营业期限时,需要校验营业期限

 代码:

<el-row type="flex" class="row-bg">
            <el-col :span="12">
              <el-form-item label="非长期营业期限">
                <el-switch v-model="businessTermAdmin"/>
              </el-form-item>
            </el-col>
            <el-col v-show="businessTermAdmin" :span="12">
              <el-form-item :rules="businessTermAdmin ? rules.businessTerm : []" label="营业期限:" prop="businessTerm">
                <el-date-picker v-model="ent.businessTerm" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" />
              </el-form-item>
            </el-col>
          </el-row>

script

rules: {
        businessTerm: [{required: true, message: '请填写营业期限', trigger: 'blur'}]
}

案例二

当有值的时候不进行校验,当没有值的时候进行校验。

如果为空,则进行校验

 代码如下:

<el-col :span="12">
          <el-form-item label="药材品名:" :rules="edit.materialName ? [] : rules.materialName" prop="materialName">
            <el-input v-model.trim="edit.materialName" class="input-with-select" disabled>
              <el-button type="primary" slot="append" icon="el-icon-search" @click="openMaterialDialog">选择</el-button>
            </el-input>
          </el-form-item>
        </el-col>

scripts

rules: {
          materialName: [{ required: true, message: '请输入品名', trigger: 'blur' }]
}

案例3

inputNumber组件校验,由于该组件有默认值,如果不输入,则仍能通过校验

解决办法:提交时,如果值为默认值(比如0)则提示“请输入。。。”

<el-form-item label="药材重量(kg):" :prop="`prepareMaterialList.${index}.materialWt`" :rules="rules.materialWt">
              <el-input-number controls-position="right" v-model="item.materialWt"
                               :min="0" :precision="3"></el-input-number>
            </el-form-item>

校验规则

rules: {
          materialWt: [{ required: true, message: '必填', trigger: 'change' }],
        }

提交时校验

// 校验药材重量
        let materialWtFlag = true
        this.prepareInfo.prepareMaterialList.forEach(material => {
          if (!material.materialWt || material.materialWt === 0) {
            materialWtFlag = false
            return
          }
        })
        if (!materialWtFlag) {
          this.$message.warning('请输入药材重量!')
          return
        }

案例4

一个label两个输入框的情况

解决办法:分两层,外层有label,内层没label,外层无prop,内层有prop

<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>

效果如下:

 

posted on 2022-05-08 10:04  周文豪  阅读(2249)  评论(0编辑  收藏  举报