CESAR NICOLINI RIVERO
CESAR NICOLINI RIVERO

Reputation: 117

how to validate hour using express-validator npm

i'm trying to use a express-validator to validate a hour. I sent this json:

{
  "hour" : "10:30",
  "day":"monday"
}  

in the following code:

var regex = new RegExp('/^(10|11|12|[1-9]):[0-5][0-9]$/');
var hour = req.body.hour;

req.check('hour',"error to add hour").matches(regex);
var errors = req.validationErrors();

if(errors){  
    res.status(400).send(errors);       
} else {
    res.status(200).json({hour:'hour ok'});
}

the program throws me the following error:

[
  {
    "param": "hour",
    "msg": "error to add hour",
    "value": "10:30"
  }
]

I think my error is in the validation of the regex. should send me {hour:'hour ok'}... please, help me!!!

Upvotes: 0

Views: 1444

Answers (1)

Mika Sundland
Mika Sundland

Reputation: 18939

I guess it works better if you use

new RegExp(/^(10|11|12|[1-9]):[0-5][0-9]$/);

or

new RegExp('^(10|11|12|[1-9]):[0-5][0-9]$');

If you use a string as an argument to the regexp constructor you have to skip the slashes at the beginning and end of the string.

Upvotes: 2

Related Questions