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

ivica.moke picture ivica.moke · Feb 26, 2019 · Viewed 11.1k times · Source

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.

Answer

Baboo_ picture Baboo_ · Feb 26, 2019

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.