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!
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)
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
})
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With