DreamsInHD
DreamsInHD

Reputation: 413

express-validator isAfter is always false

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.

Upvotes: 1

Views: 2219

Answers (2)

M. Emre Yalçın
M. Emre Yalçın

Reputation: 654

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

Upvotes: 0

dimitris tseggenes
dimitris tseggenes

Reputation: 3186

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')

Upvotes: 3

Related Questions