Conditional Validation in Yup

后端 未结 3 736
刺人心
刺人心 2020-12-29 01:28

I have an email field that only gets shown if a checkbox is selected (boolean value is true). When the form get submitted, I only what this field to be required

3条回答
  •  星月不相逢
    2020-12-29 01:53

    Totally agree with @João Cunha's answer. Just a supplement for the use case of Radio button.

    When we use radio button as condition, we can check value of string instead of boolean. e.g. is: 'Phone'

    const ValidationSchema = Yup.object().shape({
      // This is the radio button.
      preferredContact: Yup.string()
        .required('Preferred contact is required.'),
      // This is the input field.
      contactPhone: Yup.string()
        .when('preferredContact', {
          is: 'Phone',
          then: Yup.string()
            .required('Phone number is required.'),
        }),
      // This is another input field.
      contactEmail: Yup.string()
        .when('preferredContact', {
          is: 'Email',
          then: Yup.string()
            .email('Please use a valid email address.')
            .required('Email address is required.'),
        }),
    
    });
    

    This the radio button written in ReactJS, onChange method is the key to trigger the condition checking.

    
    
    

    And here's the callback function when radio button get changed. if we are using Formik, setFieldValue is the way to go.

    handleRadioButtonChange(value, setFieldValue) {
      this.setState({'preferredContact': value});
      setFieldValue('preferredContact', value);
    }
    

提交回复
热议问题