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
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')
})
});
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With