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

Vee-validate验证异常:仅提交时验证,初始加载显示全部错误

解决方案

问题原因

你的表单初始加载就显示所有错误,是因为直接将验证错误errors.xxx绑定到组件的error属性上,而必填字段初始值为空,导致验证错误一开始就存在并显示。同时缺少对错误显示时机的控制——应该仅在字段被用户触摸(输入/失去焦点)或表单提交后,才展示验证错误,同时实现输入过程中的实时验证。

修改步骤

1. 补充返回表单字段状态

在setup函数的返回对象中,添加fields属性,它包含每个字段的touched(是否被触摸)、dirty(是否修改过)等状态:

return {
  values: formValidation.values,
  submit,
  errors: formValidation.errors,
  validationMeta: formValidation.meta,
  fields: formValidation.fields, // 新增字段状态对象
  infoMessage
}

2. 配置实时验证模式

在useForm初始化时,添加mode: 'eager'配置,确保字段值变化时立即触发验证:

const formValidation = useForm({
  validationSchema: validationSchema,
  initialValues: {
    hasWebsite: 'no',
    websiteAddress: '',
    name: '',
    email: '',
    message: ''
  },
  mode: 'eager' // 开启实时验证,值变化立即验证
})

3. 控制错误显示时机

修改模板中所有表单组件的error绑定条件,仅当字段被触摸或表单已提交时,才显示对应错误:

<template>
  <h1>Contact</h1>
  <h1 v-if="infoMessage">{{ infoMessage }}</h1>
  <form @submit="submit">
    <BaseTextInput 
      label="Your Name" 
      type="text" 
      v-model="values.name" 
      :error="(fields.name.touched || validationMeta.submitted) && errors.name" 
    />
    <BaseTextInput
      label="Your email address"
      type="email"
      v-model="values.email"
      :error="(fields.email.touched || validationMeta.submitted) && errors.email"
    />
    <BaseSelect
      :choices="['yes', 'no']"
      v-model="values.hasWebsite"
      label="Do you currently have a website?"
      :selectedOption="values.hasWebsite"
      :error="(fields.hasWebsite.touched || validationMeta.submitted) && errors.hasWebsite"
    />
    <BaseTextInput
      label="What is your website address?"
      type="text"
      v-model="values.websiteAddress"
      :error="(fields.websiteAddress.touched || validationMeta.submitted) && errors.websiteAddress"
      v-if="values.hasWebsite === 'yes'"
    />
    <BaseTextInput
      label="Enter your message here:"
      type="text"
      v-model="values.message"
      :error="(fields.message.touched || validationMeta.submitted) && errors.message"
    />
    <button type="submit">Submit</button>
  </form>
</template>

效果说明

  • 初始加载时,所有字段不会显示错误提示
  • 用户开始输入某个字段(触摸字段)后,该字段会实时验证,错误会即时显示/消失
  • 表单提交后,所有不符合验证规则的字段都会显示错误,无论是否被触摸

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 07:45:01