How to validate a date using Yup in case of wrong two digit year input

Viewed 401

I'm trying to validate a date. The input field, which is a date picker could have the input 05.01.20 which results in the date Sun Jan 05 0020 00:00:00 GMT+0053. This is obviously not a useful year value, so I would expect an error message for wrong input format (which should be YYYY instead of YY - in this example 05.01.2020).

This is my attempt, which is working but hacky, as it returns a boolean value in the transform function. I guess this is not the correct validation method. Also I would like to add a minimum date value (after checking if format is valid). If date is older then Jan 1, 2000, it should throw an error.

Yup.object().shape({
    birthday: Yup.date()
    .transform((value, originalValue) => {
        const year = originalValue.getFullYear() || 0
        return year > 2000 ? originalValue : false
    })
    .typeError('Wrong format (DD.MM.YYYY)')
    .nullable()
    .required('Birthday missing')
})
0 Answers
Related