Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yup validation based on another non-required field

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
like image 518
Adrian Avatar asked Feb 06 '20 09:02

Adrian


2 Answers

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')            
        })
    });
like image 66
v.k. Avatar answered Jan 14 '23 03:01

v.k.


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}
like image 23
majran Avatar answered Jan 14 '23 03:01

majran