Conditional validation with Yup and Formik

Updated ans: 2023. you can use Yup conditions const validationSchema = Yup.object().shape({ isCompany: Yup.boolean(), companyName: Yup.string().when(‘isCompany’, { is: true, then: Yup.string().required(‘Field is required’) }), companyAddress: Yup.string().when(‘isCompany’, { is: (isCompany) => true,//just an e.g. you can return a function then: Yup.string().required(‘Field is required’), otherwise: Yup.string() }), // test an unconventional type logo: Yup.mixed() .test(‘file_size’, ‘error: file … Read more

Get the value of another field for validation in Yup Schema

number.max cannot reference other field and calculate with it at validation. If you want to do this, you need to implement own schema with mixed.test. Here is a example. tips: number() .min(0, `Minimum tip is $0`) .test({ name: ‘max’, exclusive: false, params: { }, message: ‘${path} must be less than 10% of the price’, test: … Read more

yup validation on multiple values

When using Yup if all normal features fail you, you can use the .test feature, documented here – https://github.com/jquense/yup#mixedtestname-string-message-string–function-test-function-schema mixed.test(name: string, message: string | function, test: function): Schema Adds a test function to the validation chain. Tests are run after any object is cast. Many types have some tests built in, but you can create … Read more

Yup validation with two fields related

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 > … Read more

Formik, Yup Password Strength Validation with React

You need to pass an actual RegExp object to matches, not a string. Just replace the double quotes with forward slashes in your password schema: EDIT: Updated to use regex from @Bren password: yup .string() .required(‘Please Enter your password’) .matches( /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})/, “Must Contain 8 Characters, One Uppercase, One Lowercase, One Number and One Special Case … Read more