You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vuelidate验证器函数中正确访问兄弟输入框的dirty状态?

如何在Vuelidate验证器中正确访问Vuelidate对象并优化表单验证UX?

你可以直接在Vuelidate自定义验证器中访问实例状态,替代临时ref方案,同时解决输入过程中触发错误的UX问题,具体实现如下:

1. 通过上下文参数访问Vuelidate对象

自定义验证器的第二个参数为$context,其中包含当前表单字段的Vuelidate实例,可直接获取$dirty、$touched等状态,以此控制验证逻辑的触发时机:

import { required, between } from '@vuelidate/validators'
import { useVuelidate } from '@vuelidate/core'
import { reactive } from 'vue'

export default {
  setup() {
    const form = reactive({
      minLength: 0,
      maxLength: 10
    })

    // 自定义验证规则:仅当max字段已触碰且标记为dirty时,验证最小值≤最大值
    const minLessThanMax = (value, { $v }) => {
      // 未触碰或未修改时直接返回验证通过
      if (!$v.maxLength.$touched || !$v.maxLength.$dirty) return true
      return value >= form.minLength
    }

    const validationRules = {
      minLength: {
        required,
        between: between(0, 100)
      },
      maxLength: {
        required,
        between: between(0, 100),
        minLessThanMax
      }
    }

    const $v = useVuelidate(validationRules, form)

    return { form, $v }
  }
}

2. 结合$lazy延迟验证触发时机

开启$lazy模式后,验证逻辑只会在字段被$touch(如失焦)后执行,彻底避免输入过程中实时触发错误提示:

修改验证规则,为每个验证器添加$lazy配置:

const validationRules = {
  minLength: {
    required: { $lazy: true },
    between: { $lazy: true, value: between(0, 100) }
  },
  maxLength: {
    required: { $lazy: true },
    between: { $lazy: true, value: between(0, 100) },
    minLessThanMax: { $lazy: true }
  }
}

在模板中为输入框绑定失焦事件触发$touch:

<template>
  <div>
    <input
      v-model="form.minLength"
      type="number"
      @blur="$v.minLength.$touch()"
    />
    <input
      v-model="form.maxLength"
      type="number"
      @blur="$v.maxLength.$touch()"
    />
    <!-- 错误提示仅在验证不通过且字段已触碰时显示 -->
    <span v-if="$v.maxLength.minLessThanMax.$error">最小值不能大于最大值</span>
  </div>
</template>

3. 优化错误显示逻辑

在模板中通过$v.field.$error判断是否显示错误,该属性自动结合$dirty和验证结果,确保仅在字段已修改且验证不通过时提示错误,无需额外判断状态。

内容的提问来源于stack exchange,提问作者Alarion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 18:40:03