okky
okky

Reputation: 167

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'),

Upvotes: 9

Views: 26823

Answers (5)

David Molina
David Molina

Reputation: 63

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

check('date').isDate({format: "string"}).

Upvotes: 2

ssomename
ssomename

Reputation: 545

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

Upvotes: 14

codeMaster
codeMaster

Reputation: 334

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

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

Upvotes: 6

serguitus
serguitus

Reputation: 526

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 ;-)

Upvotes: 2

David R
David R

Reputation: 15647

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!

Upvotes: 7

Related Questions