skip to Main Content

I use Yup with Formik in ReactJS app.
I have a bunch of fields that become required if any of the fields is filled.
Fortunately Yup provides a function when to address conditional validation, but since all of those fields are interdependent Yup can’t handle it out of the box.

...authRepTwoFirstName: Yup.string().when(
    [
      "authRepTwoLastName",
      "authRepTwoBusinessTitle",
      "authRepTwoJobPosition",
      "authRepTwoPhoneNumber",
      "authRepTwoEmail"
    ],
    authTwoValidationSchema
  ),
  authRepTwoLastName: Yup.string().when(
    [
      "authRepTwoFirstName",
      "authRepTwoBusinessTitle",
      "authRepTwoJobPosition",
      "authRepTwoPhoneNumber",
      "authRepTwoEmail"
    ],
    authTwoValidationSchema
  ),...

function authTwoValidationSchema(fields: string[], schema: Schema) {
  return fields.some(field => field?.length)
    ? schema.required("All fields for auth rep two need to be filled if in use")
    : schema.notRequired()
}

In the example above I get an error Cyclic dependency, node was:"authRepTwoLastName"

What would be a good strategy to solve this issue?

2

Answers


  1. Chosen as BEST ANSWER

    For anyone with a similar question, there's an answer in the spec:
    You can also prefix properties with $ to specify a property that is dependent on context passed in by validate() or cast instead of the input value.


  2. I had two interdependent fields, let’s say A and B. I got the same error. I fixed it by adding an array consisting of these two fields (like this: [‘A’, ‘B’]). It worked.

    { ... A: Yup.string().when( ... ), B: Yup.string().when( ... ), ... }, ['A', 'B']

    Make sure the array is passed after the parent of A and B, like this:
    { A: ..., B: ...}, ['A', 'B']

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search