Conditional Validation in Yup

Conditional validation with Yup and Formik

You can conditionally add to your validation schema just like any other object:

let validationShape = {
company: Yup.object().shape({
name: Yup.string().required('Field is required'),
address: Yup.string().required('Field is required'),
email: Yup.string()
.email('Wrong e-mail format')
.required('Field is required')
})
};

if (this.state.isPerson) {
validationShape.person = Yup.object().shape({
name: Yup.string().required('Field is required'),
surname: Yup.string().required('Field is required'),
middleName: Yup.string().required('Field is required'),
email: Yup.string()
.email('Wrong e-mail format')
.required('Field is required');
}

const validationSchema = Yup.object().shape(validationShape);

Yup conditional validation depending on if another field is valid?

I figured it out. I have divided the main schema into an emailSchema and a nameSchema, and then I used the concat method based on the step of the registration (1 being the step with the frist name field).

const schema = step === 1 ? emailSchema.concat(nameSchema) : emailSchema

conditional validation with yup

The construct:

.when("out", {
is: !disableOutCounterField,

compares the out value with !disableOutCounterField, and if they are equal, the then rule is applied. But quite likely they are never the same.

The check that is needed here is just the value of !disableOutCounterField by itself, for any value of out. This can be done using an expression:

.when("out", {
is: value => !disableOutCounterField,

In words: for every out value, return !disableOutCounterField, and if it returns true, apply the then part.

Formik and Yup conditional validation not working with useState

Changing the Switch value does not affect Formik's hasSpouse value.

Refactor code as below

<Switch
onValueChange={(value) => {
props.setFieldValue("hasSpouse", value);
}}
value={props.values.hasSpouse}
/>;




Related Topics



Leave a reply



Submit