express-validator isAfter is always false

2k Views Asked by At

I'm trying to validate that a certain endDate is after a startDate. I've tried everything I found and could think of but nothing works. Some examples of what I've tried:

check('endDate').isAfter(new Date('startDate')).withMessage('End date of lab must be valid and after start date')
check('endDate').isAfter(new Date('startDate').toDateString()).withMessage('End date of lab must be valid and after start date')
check('endDate').isAfter('startDate').withMessage('End date of lab must be valid and after start date')
check('endDate').isAfter(new Date('' + 'startDate').toDateString()).withMessage('End date of lab must be valid and after start date')

The docs say that isAfter() expects a string.

2

There are 2 best solutions below

0
On
query("endDate").notEmpty().custom((v, { req }) => v > req.query?.startDate)
0
On

If both startDate and endDate are input fields, you should use a custom validator in order to have access to both values:

check('endDate').custom((value, { req }) => {
    if(new Date(value) <= new Date(req.body.startDate)) {
        throw new Error ('End date of lab must be valid and after start date');
    }
    return true;
})

If startDate, is a predefined value, you can use the isAfter validator, for example

var startDate = new Date();

Then you can check the dates you want

check('endDate').isAfter(new Date(startDate).toDateString()).withMessage('End date of lab must be valid and after start date')