Nuxt3中vee-validate结合yup自定义验证触发异常求助
解决Vee-Validate + Yup自定义验证触发范围问题
问题场景
在Nuxt 3项目中使用vee-validate和yup实现表单验证时,修改任意字段的值都会触发所有字段的自定义验证规则。例如修改value1时,value1和value2的自定义test都会执行,产生不必要的性能开销。
原因分析
Vee-Validate默认验证模式为aggressive,即表单中任意字段发生变化时,会对整个表单的验证Schema做全量校验,因此所有字段的自定义规则都会被触发执行。
解决方案
通过修改useForm的验证模式为eager,让Vee-Validate仅在当前修改的字段发生变化时,只校验该字段,而非全量校验整个表单。
修改后的代码
app.vue
<template> <div> <BaseFormInput label="Value1" form-control-name="value1" /> <BaseFormInput label="Value2" form-control-name="value2" /> </div> </template> <script setup lang="ts"> import { useForm } from 'vee-validate'; import { object, string } from 'yup'; useForm({ initialValues: { value1: 'value 1', value2: 'value 2' }, // 设置验证模式为eager,仅校验当前变化的字段 mode: 'eager', validationSchema: object({ value1: string().required().test('is valid email', 'invalid email', (value: string) => { console.log("custom email validation") return value.length > 10 }), value2: string().required().test('text', 'invalid text', value => { console.log("custom text validation") return value.length > 10 }), }) }) </script>
BaseFormInput.vue(无需修改)
<template> <div> <label class="form-label">{{ label }}</label> <input v-model="value" :disabled="disabled" /> <span>{{ errorMessage }}</span> </div> </template> <script setup lang="ts"> import { useField } from 'vee-validate'; const props = defineProps<{ label: string, formControlName: string, disabled?: boolean }>(); const { value, errorMessage } = useField<string>(() => props.formControlName); </script>
验证效果
修改value1时,控制台只会打印custom email validation;修改value2时,只会打印custom text validation,实现了自定义验证仅在对应字段变化时触发的需求。
可选的其他验证模式
如果需要不同的验证时机,可选择以下模式:
lazy:仅在字段失去焦点时校验当前字段passive:仅在表单提交时校验所有字段aggressive:默认值,任意字段变化时校验所有字段
内容的提问来源于stack exchange,提问作者user3717119
相关产品推荐
相关产品推荐

