1
votes

I am trying to create a yup schema where based on a variables value the schema changes slightly. In my case depending on the value of prop myCondition I need to make a field as required. I would like to know if there is any better way I can achieve the same using Yup. Here's my current code structure that works:

// config.js
const COMMON_SCHEMA = {
  str1: yup
    .string()
    .nullable()
    .required('Please input str1'),
  str3: yup
    .string()
    .nullable()
};
const VALIDATION_SCHEMA_1 = yup.object().shape({
  ...COMMON_SCHEMA,
  str2: yup.string().nullable(),
});

const VALIDATION_SCHEMA_2 = yup.object().shape({
  ...COMMON_SCHEMA,
  str2: yup
    .string()
    .nullable()
    .required('Please input str2'),
});

const SCHEMAS = {
  VALIDATION_SCHEMA_1,
  VALIDATION_SCHEMA_2
}
export default SCHEMAS;

the following is how I conditionally choose different schemas:

// app.js
import SCHEMAS from './config';
...

<Formik
  validationSchema={
    this.props.myCondition === true
      ? SCHEMAS.VALIDATION_SCHEMA_1
      : SCHEMAS.VALIDATION_SCHEMA_2
  }
>
...
</Formik>

I feel like I can achieve whatever I am doing above in an easier way with yup. One of the approaches I tried was to pass in the prop myCondition into config file and work with it's value by using yup.when() but when only works if the value you want to use is also a part of the form so I couldn't achieve the same.

1

1 Answers

0
votes

You can conditionally add validation directly in the validationSchema, like this: https://stackoverflow.com/a/56216753/8826314

Edited to add, you can include your value in the initial form, so that you can do the when check against that field. For example:

<Formik 
  initialValues={
    ...,
    str2
  }
  validationSchema={
    ...,
    str2: yup.object().when('str2', {
      is: str2 => condition check that returns boolean,
      then: Yup.string().nullable(),
      otherwise: Yup.string().nullable().required('Please input str2')
    })
}
>
...
</Formik>