编辑:虽然接受的解决方案有效,this在我的用例中工作得更好
我有一个函数可以验证 输入字段 A 也不是 输入字段 B 是空的
并且通过我的表单构建方式,我只需要编写一个函数来检查两者。 (实际函数要复杂得多,所以我选择创建下面的示例函数)
这是我的测试功能:
function isValid(message) {
//I don't use the message variable but I added it anyway
return this.test("isValid", message, function (value) {
if(!value.A) {
return createError({path: `${this.path}.A`, message:"A is empty"});
}
if(!value.B) {
return createError({path: `${this.path}.B`, message:"B is empty"});
}
return true;
})
结果是 当 A 和 B 为空时,我返回第一个 createError 因此跳过函数的其余部分 这就是 formik.errors 对象看起来像:{
parent: {
A: "A is empty"
}
}
如何创建错误数组并将其返回? 我试过了:
返回一个 createErrors() 数组,但我得到了相同的结果,
使用带有路径和消息数组的 createErrors 但 formik.errors 看起来像这样:
{
parent.A: { parent.B: "2 errors occured" }
}
而不是 想要的 :{
parent: {
a: "A is empty",
b: "B is empty"
}
}
最佳答案
您可以使用ValidationError
来自 Yup
来实现这个目标。 ValidationError
的构造函数accepts其他数组 ValidationError
实例。个人ValidationError
实例能够容纳 path
和错误消息和父实例将combine them .
这是示例测试功能:
import { ValidationError } from 'yup'
const testFunc = (value) => {
const keys = ['A', 'B']
const errors = keys.map((key) => {
if (value[key]) { return null } // Successful validation, no error
return new ValidationError(
`${key} is empty`,
value[key],
key
)
}).filter(Boolean)
if (errors.length === 0) { return true }
return new ValidationError(errors)
}
也可以用 createError
做同样的事情。根据 the source code 判断.您可以将函数而不是字符串传递给
message
createError
的属性(property)称呼。在这种情况下,函数将在 createError
内调用。 => ValidationError.formatError
here .如果这个函数返回一个正确构建的数组 VaildationError
实例我们会得到相同的结果。这是该方法的示例测试函数:
import { ValidationError } from 'yup'
const testFunc = (value, { createError }) => {
const keys = ['A', 'B']
const errors = keys.map((key) => {
if (value[key]) { return null } // Successful validation, no error
return new ValidationError(
`${key} is empty`,
value[key],
key
)
}).filter(Boolean)
if (errors.length === 0) { return true }
return createError({
message: () => errors
})
}
关于javascript - (是的)如何使用单个 .test() 函数创建多个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68777401/