Express Validator to validate DateTime
Asked Answered
S

5

9

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'),
Salable answered 10/7, 2018 at 14:25 Comment(0)
A
7

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!

Anatase answered 10/7, 2018 at 14:35 Comment(1)
getting error SyntaxError: Octal escape sequences are not allowed in strict mode.Staphylorrhaphy
S
13

The express-validator documentation does it like so now:
check('date-of-birth').isISO8601().toDate(),

source: Validation Chain API v6 Example
Validation Chain API v7

Scape answered 28/9, 2021 at 7:46 Comment(1)
How to use this in schema? I can't find anything in the docs...Barrage
A
7

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!

Anatase answered 10/7, 2018 at 14:35 Comment(1)
getting error SyntaxError: Octal escape sequences are not allowed in strict mode.Staphylorrhaphy
E
5

To Validate this format= "2022-09-09T00:00:00" as string from HTML form

check('holiday.day').isISO8601().toDate()
            .withMessage("Invalid day received")

Eolian answered 9/9, 2022 at 12:18 Comment(0)
C
2

As of 2021 this can be done by using isISO8601(str) from validator library (which express-validator uses behind the scene). More info on ISO8601 here Hope this helps ;-)

Ciri answered 27/8, 2021 at 15:11 Comment(0)
B
1

In 2024 you can use the standard validator .isDate() e.g

check('date').isDate({format: "string"}).
Barrios answered 22/4, 2024 at 2:6 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.