8
votes

I'm building a form in React using Formik and React-bootstrap and I'm using Yup to validate the form.

I have 2 fields, let's say FieldA and FieldB. FieldA is not required but FieldB is required if FieldA is not empty.

FieldA is a textbox while FieldB is multiple select. My validation rule for FieldB must be:

FieldA !=='' ? FieldB is required : do nothing
2

2 Answers

20
votes

Try this:

const schema = Yup.object().shape({
       FieldA: Yup.string(),
       FieldB: Yup.string()
        .when('FieldA', {
          is: (FieldA) => FieldA.length > 0,
          then: Yup.string()
            .required('Field is required')            
        })
    });
1
votes

Use the validate option in Formkit as mentioned here

const validate = values =>
  if (values.a > values.b){
    //return error message for assumed filed
    return {
      a: 'a is greater than b',
    };
  }

in Formkit:

<Formik
    initialValues={{
    a: 2,
    b: 1,
    }}
    validate={validate}