如何在V-Rules中实现重复分类选择时显示错误提示
解决重复分类的VeeValidate错误提示问题
你的代码存在两个关键问题,导致无法正确触发重复分类的错误提示:
- 第二个验证规则的箭头函数使用了大括号但未返回任何值,VeeValidate无法识别验证结果
- 验证逻辑的返回值不符合VeeValidate规则要求:规则返回
true表示验证通过,返回字符串表示验证失败并显示该错误提示;而你的checkForDuplicateCategory返回true时是存在重复(应验证失败),逻辑完全相反
修正方案一:直接在规则内处理逻辑
修改categoryRules,直接在规则里判断重复情况,同时修正返回逻辑:
categoryRules: [ v => !!v && !/^\s+$/.test(v) || "Invoice type is required", v => { const selectedCategory = v?.toLowerCase(); // 检查newEstimates中是否已存在相同分类(忽略大小写) const isDuplicate = this.newEstimates.some(estimate => estimate.category?.toLowerCase() === selectedCategory ); // 无重复则返回true(验证通过),否则返回错误提示字符串 return !isDuplicate || "Duplicate Category not permitted"; } ]
修正方案二:复用现有函数并调整逻辑
如果想保留checkForDuplicateCategory函数,需要调整函数返回值,同时修正规则写法:
// 调整函数:返回true表示存在重复,false表示无重复 checkForDuplicateCategory(selectedCategory){ const lowerCaseSelected = selectedCategory?.toLowerCase(); return this.newEstimates.some(estimate => estimate.category?.toLowerCase() === lowerCaseSelected ); } // 修正验证规则 categoryRules: [ v => !!v && !/^\s+$/.test(v) || "Invoice type is required", // 无重复则验证通过(返回true),否则返回错误提示 v => !this.checkForDuplicateCategory(v) || "Duplicate Category not permitted" ]
关键注意点
- 不要在规则的箭头函数里用大括号却不写
return,否则VeeValidate会认为验证结果是undefined,视为验证失败但不会显示自定义错误 - 始终确保验证规则的返回值符合要求:验证通过返回
true,验证失败返回错误提示字符串
内容的提问来源于stack exchange,提问作者Somasekhar
相关产品推荐
相关产品推荐

