最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript regex validation issue with time format - Stack Overflow

programmeradmin3浏览0评论

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;

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;
Share Improve this question asked Sep 11, 2013 at 8:24 KodeFor.MeKodeFor.Me 13.5k28 gold badges101 silver badges172 bronze badges 1
  • Thanks every one for tha response !! :) – KodeFor.Me Commented Sep 11, 2013 at 8:29
Add a ment  | 

4 Answers 4

Reset to default 11

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

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

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.

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

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./40vuj

发布评论

评论列表(0)

  1. 暂无评论