so i have a problem with conditional validation using yup.
Basically i want shipping to have required properties when the checkbox is not toggled.
I am using yup's when feature and i can't figure out how to reference the sameShippingAsBilling boolean value from that shipping nested object.
When checkbox is false, everything is working fine, errors are shown...
But when checkbox is checked, i get this error: "Cannot use 'in' operator to search for 'default' in undefined"
The problem is that the value in is callback is undefined.
Is it even possible to access the outer variables in when from those nested objects or not. What is the alternative way to do this?
Here is the sandbox example
const schema = Yup.object({
sameShippingAsBilling: Yup.bool(),
billing: Yup.object({
line1: Yup.string().required(),
city: Yup.string().required(),
country: Yup.string().required()
}),
shipping: Yup.object({
line1: Yup.string().when("sameShippingAsBilling", {
is: !val || val === false,
then: Yup.string().required(),
}),
city: Yup.string().when("sameShippingAsBilling", {
is: !val || val === false,
then: Yup.string().required(),
}),
country: Yup.string().when("sameShippingAsBilling", {
is: !val || val === false,
then: Yup.string().required(),
})
})
});
const addrValues = { line1: "", city: "", country: "" };
const formOpts = {
mode: "onChange",
reValidateMode: "onChange",
defaultValues: {
sameShippingAsBilling: true,
billing: { ...addrValues },
shipping: { ...addrValues }
},
resolver: yupResolver(schema)
};
export default function CheckoutForm() {
const methods = useForm(formOpts);
const { watch } = methods;
const shippingAsBilling = watch("sameShippingAsBilling");
const onSubmit = async (data) => {
console.log(data);
};
return (
<MuiThemeProvider theme={createMuiTheme()}>
<FormProvider {...methods}>
<form onSubmit={methods.handleSubmit(onSubmit)} noValidate>
<pre>errors: {JSON.stringify(methods.errors, null, 2)}</pre>
<div className="group">
<FormTextField name="billing.line1" />
<FormTextField name="billing.city" />
<FormTextField name="billing.country" />
</div>
<div>
<FormCheckbox name="sameShippingAsBilling" />
</div>
{!shippingAsBilling && (
<div className="group">
<FormTextField name="shipping.line1" />
<FormTextField name="shipping.city" />
<FormTextField name="shipping.country" />
</div>
)}
<div>
<button type="submit">Pay</button>
</div>
</form>
</FormProvider>
</MuiThemeProvider>
);
}