[英]How to make Yup field which is object, required if other field is true. -Yup validation
I'm new to using Yup validation.我是使用 Yup 验证的新手。 I'm trying to achieve making fields required based on condition.
我正在尝试根据条件制作所需的字段。 as u can see below I want to make this digital object required only if
hasDigital
is true other wise keep it optional, I tried below approach but it always says digital.pages
is required , even when I'm passing hasDigital false.正如您在下面看到的那样,我想让这个数字对象只有在
hasDigital
为真时才需要,否则保持它是可选的,我尝试了下面的方法,但它总是说digital.pages
是必需的,即使我传递 hasDigital 为假。 I tried by removing required
tag from hasDigital
but still facing same issue.我尝试从
hasDigital
中删除required
的标签,但仍然面临同样的问题。
I don't know what am I doing wrong, thanks In advance for any help.我不知道我做错了什么,在此先感谢您的帮助。
const validationSchema=Yup.object({
hasDigital:Yup.boolean().required(),
digital:Yup.Object({
pages:Yup.number().required(),
price:Yup.number().required()
}).when("hasDigital", {
is:true ,
then: Yup.object().required(),
otherwise:Yup.object().optional()})
})
I had a similar problem, and I got it this way!我有类似的问题,我是这样解决的!
const digitalSchema = yup.object().shape({
pages: yup.number().required(),
price: yup.number().required(),
});
const validationSchema = yup.object().shape({
hasDigital: yup.boolean().required(),
digital: yup.object().when('hasDigital', {
is: true,
then: digitalSchema,
}),
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.