Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express-validator : How to validate "start date" is before "end date"

I am using express-validator to do my server validation and I have come across a little trouble with my date validation. I am trying to validate that my Start Date is before my End Date. I am currently using this:

check('taskStartDate', { isBefore : ('taskEndDate' === undefined ) })
.isBefore('taskEndDate').withMessage('Start Date must be before End Date')

However, the problem with that is no matter what date I input into my form, whether the start date is before or after the end date, I get my implemented message 'Start Date must be before End Date'. I don't know how else to go about doing this besides a custom validator, which if that is the recommended way, I would appreciate any guidance on how to go about writing the custom validation. I also tried to include sanitization like so:

check('taskStartDate').isBefore(sanitizeBody('taskEndDate').toDate())
.withMessage( 'Start Date must be before End Date.')

but that did not work either. Any help would be greatly appreciated!

like image 692
bpp Avatar asked Sep 14 '25 00:09

bpp


2 Answers

express-validator uses underlying validator.js, so all validator.js middlewares are available in express-validator as well.

check [validator.js]: https://github.com/validatorjs/validator.js#validators for complete list

there is .isAfter() and isBefore().

you can implement this way

check('dateOfMissing', 'Date cannot be in future').Before('dateOfMissing', ['timeinpast']),
check('dateOfMissing', 'Date cannot be in future').isAfter('dateOfMissing', ['time in future']);

default is now (current date)

like image 169
Muhammad Uzair Avatar answered Sep 16 '25 16:09

Muhammad Uzair


As @gustavohenke wrote, you should create custom validator. Code below is for express-validator version 13.7.0. Main difference to @gustavohenke example is changed validation function to check() and in current version this function must return true at the end.

[
    check('end').toDate(),
    check('start').toDate().custom((startDate, { req }) => {
        if (startDate.getTime() > req.body.end.getTime()) {
            throw new Error('start date must be before end date');
        }
        return true
    })
];
like image 40
c97 Avatar answered Sep 16 '25 17:09

c97