I am working on a form that is made with Formik, Yup, and ReactJS. In the date field, I am trying to validate if the user is 18 years old. I have passed the following as validationSchema paremeter in Formik:
import differenceInYears from "date-fns/differenceInYears";
...
...
...
dob: Yup.date()
.nullable()
.test("dob", "Should be greater than 18", function (value) {
return differenceInYears(value, new Date()) >= 18;
}),
The name of the formik input field is dob
. But it shows the validation error even if I enter a valid date which is 18 years old. So, how to validate it properly?
You need to swap the date params:
differenceInYears(new Date(), new Date(value)) >= 18;
If you check date-fns docs, the first argument should be the later date.
Also you need to parse the field value into a Date
.