给出以下是的架构:
const myValSchema = Yup.object().shape({
myGroups: Yup.array()
.of(
Yup.object().shape({
myName: Yup.string()
.required('Name is required')
mySelection: Yup.number().required('Selection is required'),
myHobbies: Yup.array().of(
Yup.object().shape({
hobbyName: Yup.string()
.required('Hobby name is required'),
hobbyLikes: Yup.number()
.nullable()
.when("dummy", {
is: (value) =>
mySelection === 99,
then: Yup.number().typeError('Value must be a number').required('Likes is required').positive(),
}),
})
)
})
)
});
仅当此形状之外的 mySelection
值等于 99 时,我才需要验证 hobbyLikes
,但我不确定如何访问此外部值。
只是不确定如何实现这一目标。
最佳答案
有a GitHub issue对于这个要求,但目前,它已经关闭,似乎这个问题只有变通的解决方案。
您可以通过使用自定义 test()
而不是使用 when() 来使用
访问父值:context.options.from[1]
来使用此解决方案
const myValSchema = Yup.object().shape({
myGroups: Yup.array().of(
Yup.object().shape({
myName: Yup.string().required("Name is required"),
mySelection: Yup.number().required("Selection is required"),
myHobbies: Yup.array().of(
Yup.object().shape({
hobbyName: Yup.string().required("Hobby name is required"),
hobbyLikes: Yup.number()
.nullable()
.test("isSelection", "Likes is required", (value, context) => {
const currentSelectionValue =
context.options.from[1].value.mySelection;
if (
currentSelectionValue === "99" ||
currentSelectionValue === 99
) {
return value > 0;
}
return true;
})
})
)
})
)
});
您可以看看this sandbox有关此解决方案的实时工作示例。
关于javascript - 是的,基于较高值的较低级别验证 - 不确定如何访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73724613/