1
votes

I have a validation schema object:

SCHEMA = object().shape({
  ...
  someField: string().required(validation_keys.required),
  ...
});

I am using useFormik within my component:

const formik = useFormik({
  initialValues: values,
  onSubmit: ...,
  validationSchema: SCHEMA,
});

I was looking for a way to pass an argument to my SCHEMA, so as someField would be required just when the argument is true... I read about context, also tried to do it with when(), but none of these worked for me...

My goal is to validate someField base on a component prop, not other field from formik. Something similar to the example below:

validationSchema={yup.object().shape({
    someField: yup
      .string()
      .when("xxx", {
        is: true,
        then: yup.string().required("Required"),
        otherwise: yup.string(),

      })
  })
}

xxx is supposed to be passed to validation schema in my React component where useFormik is used

2
Does this answer your question? Conditional Validation in YupNik
Nope, this is conditional validation base on some other field. I want to validate a field base on a React component prop, not field.jake-ferguson
added now, I think it is clear nowjake-ferguson

2 Answers

0
votes

You can do something like this.

    const validationSchema= Yup.object({
      custom_field: Yup.string().test(
        "match",
        "Custom validation enabled",
        function () {
          if (!shouldFormValidate) return true;
          return false;
        }
      )
    });

Here the working codesandbox.

0
votes

If you want to validate a field based on a React component prop you can use withMutation:

schema = object({
  ...,
  someField: string(),
  ...
});

if(validation_keys.required) {
  schema.fields.someField.withMutation(schema => {
    schema.required();
  });
}

Example

Edit adoring-yonath-t7kcc