Skip to content
Advertisement

Validate Field in Yup based on multiple related field values with Yup.ref and .test

I’ve created a multi-step form in “react”: “^17.0.1”, “yup”: “^0.29.3”, and “formik”: “^2.2.3”.

I want to check that when a user enters in a their Birth Day (dobD) that it is valid based on Birth Month (dobM) and Birth Year (dobY).

I have 3 separate inputs. dobM, dobD, dobY

The first check for dobD works (i.e the user can only enter a value between 1 and 31) however it doesn’t validate correctly if it a month with less than 31 days (for example June or September) OR if the month is February (which only 28 days except for leap years).

I tried using Yup.ref to reference the year and month fields inside of the day field validation, however if I type for the month 04, the user can still enter 31 which is incorrect (since April (04) only has 30 days).

Any ideas how can I fix this? Thank you!

Here is the validation in Yup I’m currently using:

JavaScript

Advertisement

Answer

Posting my solution in hopes that this helps someone else.

I was using Yup.ref incorrectly (Yup.ref(‘fieldname’) is an object, not a single value).

** To be able to access another field in Yup I converted from an arrow function to a regular function in my test, and then could access the field values using

this.options.parent.FIELD_NAME

seen in this example:

JavaScript

Full DOB validation:

JavaScript

Sidenote: For readability, I moved each check for dobD into it’s own Yup .test(), however it’s not required.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement