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

时间:2018-07-23 14:14:57

标签: validation express express-validator validator.js

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!

3 个答案:

答案 0 :(得分:1)

express-validator 使用底层的validator.js,所以所有validator.js 中间件也可以在express-validator 中使用。

检查 [验证器.js]:https://github.com/validatorjs/validator.js#validators 完整列表

有 .isAfter() 和 isBefore()。

你可以这样实现

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

默认为现在(当前日期)

答案 1 :(得分:0)

是的,当您要针对请求中的另一个值检查值时,可以使用自定义验证器。

您可能会对以下消毒剂和验证器的组合感兴趣(消毒剂在验证器之前运行,因此使用它们时,您可以将其作为Date对象的值)

[
  sanitize('taskEndDate').toDate(),
  check('taskStartDate').toDate().custom((startDate, { req }) => {
    if (startDate.getTime() >= req.body.taskEndDate.getTime()) {
      throw new Error('start date must be before end date');
    }
  })
]

Look at the docs以获取更多示例。

答案 2 :(得分:0)

这是一个自定义验证器,用于检查输入的出生日期(dob)是否有效,即今天的日期之前。

check('dob').custom(value=>{
    let enteredDate=new Date(value);
    let todaysDate=new Date();
    if(enteredDate>todaysDate){
        throw new Error("Invalid Date");
    }
    return true;
})

dob =出生日期的输入字段名称