Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript regex validation issue with time format

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;
like image 735
KodeFor.Me Avatar asked Dec 15 '25 12:12

KodeFor.Me


1 Answers

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

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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!