How to validate min age with yup and moment.js?
Asked Answered
H

3

6

I have created some registrationSchema

 export const registrationSchema = (translate) => Yup.object().shape({
  //... other properties that are validated.
  //       for example username
    username: Yup.string()
    .min(6, translate('validation:common.username.min', { min: 6 }))
    .max(20, translate('validation:common.username.max', { max: 20 }))
    .required(translate('validation:common.username.required')),
     DOB: Yup.lazy(value => {
        console.log('yup', value);
        if (moment().diff(moment(value), 'years') < 18)
          // Here return DOB error somehow
      })
    ...

and so far it works like a charm. But now i need to validate if user is minimum 18y old.I get DateOfBirth from date picker, and i can check if it's less than 18 with moment.

if(moment().diff(moment(date),'years) < 18)

and this date value i got when using Yup.lazy, but don't know how to throw validation error if under 18years to -display it under DOB field. i don't even know if i use correct yup method. I wanted to use yup.date(). but how to get picked date inside schema to check if it is valid age.

Halie answered 26/2, 2019 at 14:58 Comment(1)
could you explain, plaese, what does mean lazy in YUP, I cannt understand it from docs..Meetinghouse
A
18

You can use Yup.string like this:

Yup.string().test(
  "DOB",
  "error message",
  value => {
    return moment().diff(moment(value),'years') >= 18;
  }
)

if the test function returns true, the fields pass the test. Else an error is set.

Alt answered 26/2, 2019 at 15:31 Comment(2)
Thanks mate. I have tried with .test(), but used it completely wrong :) This works like a charm. ThanksHalie
Also, if you use a normal function(value) { ... } in the 3rd parameter (instead of an arrow function), you have access to a special this context which allows you to do things like return a custom error message: return this.createError({ message: 'Your custom message' }); for situations where you might have different error messages depending on the value.Stabler
C
1

Starting from Baboo response, using date-dns:

import differenceInYears from 'date-fns/differenceInYears';


yup
    .string()
    .required('DOB is required')
    .test('DOB', 'You must be adult', value => {
      return differenceInYears(new Date(), new Date(value)) >= 18;
    })
Civism answered 7/9, 2022 at 10:11 Comment(0)
P
0

Yup.string()
.required("DOB is Required")
.test(
  "DOB",
  "Please choose a valid date of birth",
  (date) => moment().diff(moment(date), "years") >= 18
)
Poland answered 3/10, 2021 at 8:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.