vue自定义校验规则的动态必填字段

<el-col :span="12">
    <elian-table-form-item label="有效期" prop="checkSelfTime"
    :rules="[
      {
        required: checkSelfAttShow,
        validator: checkSelfTimeRequired,
        trigger: 'blur'
      }
    ]">
    <elian-date-picker
      name="checkSelfTime"
      :start-time.sync="form.checkSelfBegnTime"
      :end-time.sync="form.checkSelfEndTime">
    </elian-date-picker>
  </elian-table-form-item>
</el-col>
  data() {
    return {
      checkSelfAttShow: false,
      checkSelfTimeRequired:(rule, value, callback) => {
        if (!this.form.checkSelfBegnTime && this.getCheckSelfAttShow()) {
          callback(new Error('有效期开始日期必填'))
        } else if (!this.form.checkSelfEndTime && this.getCheckSelfAttShow()) {
          callback(new Error('有效期截止日期必填'))
        } else {
          callback()
        }
      },
    }
  }
<--form.checkSelfAtt是监听的数据,有值才下面有效期才必填-->
  watch: {
    'form.checkSelfAtt'(){
      this.$nextTick(() =>{
        this.checkSelfTimeShowChange()
      })
    },
  },
  methods: {
    checkSelfTimeShowChange(){
      this.checkSelfAttShow = this.form.checkSelfAtt?true:false
    },
    getCheckSelfAttShow(){
      return this.checkSelfAttShow
    },
  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你正在使用 Ant Design Vue 表单,可以通过在字段的 `rules` 属性中设置自定义校验规则动态校验必填字段。 以下是一个示例: ```vue <template> <a-form ref="form" :model="form" :rules="rules"> <a-form-item label="Username" :validate-status="validateStatus('username')" :help="help('username')"> <a-input v-model="form.username" /> </a-form-item> <a-form-item label="Password" :validate-status="validateStatus('password')" :help="help('password')"> <a-input v-model="form.password" /> </a-form-item> <a-button type="primary" @click="submitForm">Submit</a-button> </a-form> </template> <script> export default { data() { return { form: { username: '', password: '', }, rules: { username: [{ required: true, message: 'Please enter username', trigger: 'blur' }], password: [{ required: false, message: 'Please enter password', trigger: 'blur' }], }, }; }, methods: { submitForm() { this.$refs.form.validate((valid) => { if (valid) { console.log('Form submitted successfully'); } else { console.log('Form validation failed'); } }); }, validateStatus(fieldName) { const field = this.$refs.form.fields[fieldName]; return field && field.errors.length > 0 ? 'error' : ''; }, help(fieldName) { const field = this.$refs.form.fields[fieldName]; return field && field.errors[0]; }, }, }; </script> ``` 在上面的示例中,`rules` 对象用于设置校验规则。`username` 字段被标记为必填字段,而 `password` 字段是可选的。当用户提交表单时,`submitForm` 方法会调用 `this.$refs.form.validate` 方法来进行表单验证。如果验证失败,则会在相应字段下方显示错误消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值