我如何在yup中放置至少需要两个字段的验证?
请在这里勾选代码框,点击这里
const validationSearch = yup.object().shape({
instagramProfileId: yup
.string()
.when(["$tiktokProfileId", "$youtubeProfileId"], {
is: (tiktokProfileId, youtubeProfileId) =>
tiktokProfileId && youtubeProfileId,
then: yup.string().notRequired(),
otherwise: yup.string().required()
}),
tiktokProfileId: yup
.string()
.when(["$instagramProfileId", "$youtubeProfileId"], {
is: (instagramProfileId, youtubeProfileId) =>
instagramProfileId && youtubeProfileId,
then: yup.string().notRequired(),
otherwise: yup.string().required()
}),
youtubeProfileId: yup
.string()
.when(["$instagramProfileId", "$tiktokProfileId"], {
is: (instagramProfileId, tiktokProfileId) =>
instagramProfileId && tiktokProfileId,
then: yup.string().notRequired(),
otherwise: yup.string().required()
})
});
将validationSearch函数替换为:
删除所有'$'并在末尾添加一个数组,其中包含每个"when">
const validationSearch = yup.object().shape(
{
instagramProfileId: yup
.string()
.when(["tiktokProfileId", "youtubeProfileId"], {
is: (tiktokProfileId, youtubeProfileId) =>
tiktokProfileId && youtubeProfileId,
then: yup.string().notRequired(),
otherwise: yup.string().required()
}),
tiktokProfileId: yup
.string()
.when(["instagramProfileId", "youtubeProfileId"], {
is: (instagramProfileId, youtubeProfileId) =>
instagramProfileId && youtubeProfileId,
then: yup.string().notRequired(),
otherwise: yup.string().required()
}),
youtubeProfileId: yup
.string()
.when(["instagramProfileId", "tiktokProfileId"], {
is: (instagramProfileId, tiktokProfileId) =>
instagramProfileId && tiktokProfileId,
then: yup.string().notRequired(),
otherwise: yup.string().required()
})
},
[
["tiktokProfileId", "youtubeProfileId"],
["instagramProfileId", "youtubeProfileId"],
["instagramProfileId", "tiktokProfileId"]
]
);
: Stackblitz