这是我的aaray :
translator_services: (4) [empty × 3, {translator_category_description: "sa",translator_category_id: "6672a5a8b07e9bc1b7e36a5c",translator_category_type_id: ['6672a5a8b07e9bc1b7e36a5a']}]
这是Yup的错误:
translator_services: Array(3)<br>
0: {translator_category_id: 'Required', translator_category_description: 'Description is required.'}<br>
1: {translator_category_id: 'Required', translator_category_description: 'Description is required.'}<br>
2: {translator_category_id: 'Required', translator_category_description: 'Description is required.'}<br>
这是验证码:
translator_services: Yup.array().of(
Yup.object().shape({
translator_category_id:
Yup.string().required("Required"),
translator_category_description:
Yup.string().nullable().required("Description is required."),
translator_category_type_id: Yup.array().nullable().min(
1,
"Select at least one service type"
),
})
),
仅应验证数组值是否已定义或不为空,否则跳过验证。 预先感谢
在这种情况下,您需要使用
.when()
函数。
这是有关它的文档:https://github.com/jquense/yup?tab=readme-ov-file#schemawhenkeys-string--string-builder-object--values-any-schema--schema-schema
所以,你的代码可能是这样的:
translator_services: Yup.array().of(
Yup.object().shape({
translator_category_id: Yup.string()
.when('translator_category_type_id', {
is: (val) => val.length,
then: Yup.string().required("Required"), // If translator_category_type_id has values, then translator_category_id is required
otherwise: Yup.string(),
}),
translator_category_description: Yup.string().nullable()
.when('translator_category_type_id', {
is: (val) => val.length,
then: Yup.string().required("Description is required."),// If translator_category_type_id has values, then translator_category_description is required
otherwise: Yup.string(),
}),
translator_category_type_id: Yup.array().nullable().min(
1,
"Select at least one service type"
),
})
)
希望有帮助!