Yup validation with two fields related

Hans Poo picture Hans Poo · Mar 27, 2018 · Viewed 15k times · Source

I'm using formik for form management in reactjs, i have a question on validation with yup.

I have two fields, ones is a select control to select the country, and the other one is a zipcode.

In the country array we have the regex to validate the zipcode, and the idea is to validate the entered zipcode using the regex of the currently selected country, someone can give a clue on how to do this.

Answer

grumpyTofu picture grumpyTofu · Jun 11, 2020

An example of a field that requires a numeric value that cannot be higher than the multiplication of two other field's values

const validationSchema = Yup.object().shape({
    num1: Yup.number().positive().required('This field is required.'),
    num2: Yup.number().positive().required('This field is required.'),
    num3: Yup.number().positive().required('This field is required.').when(['num1', 'num2'], (num1, num2, schema) => {
        return num1 > 0 && num2 > 0 ? schema.max(num1 / num2) : schema.max(0);
    })
});