Search code examples
javascriptnode.jsvalidationexpress

Express Validator to validate DateTime


I want to validate DateTime like this code below

{
    "data": {
        "start": "2018-05-12 08:00:00"
    }
}

How to combine isISO8601() and match(regex) to validate date & time in start

body('*.start')
  .exists()
  .not()
  .isEmpty()
  .withMessage('start cannot be empty')
  .isISO8601('yyyy-mm-dd')
  .matches('^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$')
  .withMessage('start must be in correct format yyyy:mm:dd hh:mm:ss'),

Solution

  • Unfortunately having datetime validation is currently unavailable with express-validator.

    Meanwhile you can go for a pure regex, which will be,

    .matches('/^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/)
    

    Hope this helps!