Search code examples
javascriptreactjsdatepickerformik

Datepicker validation using Yup


I have created a date picker using formik and I have to do the validation using Yup.

Ex: If my age is 18 by comparing it to the current date and if I select a date from the date picker more than 18, then it should give me a message my age is less than 18


Solution

  •     const YourSettingSchema = Yup.object().shape({
      dateOfBirth: Yup.string()
        .nullable()
        .test('Date of Birth', 'Should be greather than 18', function(value) {
          return moment().diff(moment(value), 'years') >= 18;
        }),
    });