I need to validate the form as follows: all fields in the form are optional, but if at least one field has a value entered, they all become mandatory.
I wrote:
const getRequiredSchema = () => {
return Yup.string().when(["full_name", "email", "password"], {
is: (...args) => args.some((item) => !!item),
then: Yup.string().required("Required!")
});
};
...
validationSchema: Yup.object({
full_name: getRequiredSchema(),
email: getRequiredSchema(),
password: getRequiredSchema()
})
And got an error: Cyclic dependency, node was:"password"
OK, I rewrote the code, trying to get rid of looping:
const getRequiredSchema = (field) => {
return Yup.string().when(
["full_name", "email", "password"].filter((f) => f !== field),
{
is: (...args) => args.some((item) => !!item),
then: Yup.string().required("Required!")
}
);
};
....
validationSchema: Yup.object({
full_name: getRequiredSchema("full_name"),
email: getRequiredSchema("email"),
password: getRequiredSchema("password")
})
But the error did not disappear. How to write validation correctly?
Here is the full cole on codesandbox
2
Answers
You can try this code, If you want to stick with Yup, one workaround could be to remove the circular dependency by creating a custom validation function that checks if at least one field has a value.
Try Yup Lazy
Working example: https://codesandbox.io/s/react-formik-yup-forked-s6w7y3?file=/src/App.js