Formik Yup date validation - accept European DD/MM/YYYY format

Viewed 3512

I am trying to use Yup with Formik for my user profile screen. The validation works fine but it expects the format of the date entered by the user to be in USA format MM/DD/YYYY rather than the application required European/UK standard format DD/MM/YYYY. Entering 31/12/1995 fails validation.

  dateOfBirth: Yup.date()
      .required("Date of Birth is required")
      .max(dateToday, "Future date not allowed")

I have searched through the Yup docs and SO but I can't work out how to do this. Any ideas?

2 Answers

I had this same issue myself and resolved it using the example in the Yup README replacing MomentJS with date-fns which is what I use for date manipulation.

Value returns Invalid Date before you custom transform is applied so you must use the original value and context to check to see if you need to run the transform logic at all and if so run it on the value from the field and not the transformed value.

Yup transform docs and date example

import { parse } from 'date-fns';    

[...]

date()
  .transform((value, originalValue, context) => {
      // check to see if the previous transform already parsed the date
      if (context.isType(value)) return value;

      // Date parsing failed in previous transform
      // Parse the date as a euro formatted date string or returns Invalid Date
      return parse(originalValue, 'dd/MM/yyyy', new Date());
})

This works perfectly for me and works for both US and UK date formats (you will still need to perform manipulation on the date if its in the us format as it will submit this value as valid)

If you ONLY want UK/Euro dates then just remove the context type check

.transform((value, originalValue) => parse(originalValue, 'dd/MM/yyyy', new Date()))

You can use the transform method to parse value. Like:

startDate: Yup.date()
    .transform(value => {
      return value ? moment(value).toDate() : value;
    })
    .required("Date of Birth is required")
    .max(dateToday, "Future date not allowed");
Related