3

I try to validate a time valie with the following script but the second value does not validate for some reason. Is there anything wrong on my script ?

var timeFormat      =   /^([0-9]{2})\:([0-9]{2})$/g;
var time_one        =   '00:00';
var time_two        =   '15:20';

if(timeFormat.test(time_one) == false)
{
    console.log('Time one is wrong');
}
else if(timeFormat.test(time_two) == false)
{
    console.log('Time two is wrong');
}

The above script returns always the Time two is wrong in my console. Also I have try to set the value of the time_two to '00:00' but again does not validate.

Is my regex wrong ?

NOTE : I also have try the following regex, but still with the same effect:

var timeFormat      =    /(\d{2}\:\d{2})/g;
KodeFor.Me
  • 13,069
  • 27
  • 98
  • 166

4 Answers4

11

I think it comes from the "global" flag, try this instead :

var timeFormat = /^([0-9]{2})\:([0-9]{2})$/;
1

test will progress a global regexp by one match, and rewind when it gets to the end of the string.

var timeFormat      =   /^([0-9]{2})\:([0-9]{2})$/g;
var time_one        =   '00:00';

timeFormat.test(time_one)  // => true   finds 00:00
timeFormat.test(time_one)  // => false  no more matches
timeFormat.test(time_one)  // => true   restarts and finds 00:00 again

So you need to lose the g flag in your scenario.

Amadan
  • 191,408
  • 23
  • 240
  • 301
1

May I propose the following options:

/^[01]?\d:[0-5]\d( (am|pm))?$/i  // matches non-military time, e.g. 11:59 pm

/^[0-2]\d:[0-5]\d$/              // matches only military time, e.g. 23:59

/^[0-2]?\d:[0-5]\d( (am|pm))?$/i // matches either, but allows invalid values 
                                 // such as 23:59 pm
Michael L.
  • 620
  • 3
  • 17
0

Simple with

/^([01]\d|2[0-3]):?([0-5]\d)$/

output:

12:12 -> OK
00:00 -> OK
23:59 -> OK
24:00 -> NG
12:60 -> NG
9:40 -> NG

Demo: https://regexr.com/40vuj

Tính Ngô Quang
  • 4,400
  • 1
  • 33
  • 33