How did I do?*

Validate month and day using express-validator

I had a requirement to allow users to specify the date on which holidays carried-over from the previous year would expire if not used up - a common practise for employers (in the UK at least) which gives employees to freedom to save unused holidays, but discourage them from hoarding them for years.

The value is a general rule to apply regardless of the year, so only the month and day need to be stored. Calculations can just append the current year using new Date().getFullYear()).

This rule validates an optional date, which must be provided in the MM-dd format - essentially ISO8601 without the year.

The optional configuration needed to be falsy in my example because JSON parses an empty field as an empty string, and the default optional rule only triggers on undefined. This meant that if no value was provided, it parsed as '', which was considered non-null by the validator, which then caused the validator's regex rule to trigger and fail validation because the pattern wouldn't match. The falsy optional rule includes undefined, null and empty strings.

body('carryOverDaysCutoff')
    .custom((value) => {
        const monthAndDayPattern = new RegExp('(0[1-9]|1[1,2])-(0[1-9]|[12][0-9]|3[01])')
        return monthAndDayPattern.test(value)
    })
    .withMessage('Provide the day and month in which carried-over days from the previous year will expire (e.g. \"12-31\" for 31st December')
    .optional({ values: 'falsy' }),