Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  151] [ 1]  / answers: 1 / hits: 9750  / 4 Years ago, mon, october 19, 2020, 12:00:00

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?


More From » reactjs

 Answers
3

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.


[#2460] Wednesday, October 14, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
arthur

Total Points: 729
Total Questions: 107
Total Answers: 109

Location: China
Member since Mon, Aug 22, 2022
2 Years ago
;