JavaScript正则表达式验证时间格式问题

3
我尝试使用以下脚本验证时间值,但第二个值由于某些原因无法验证。我的脚本有什么问题吗?
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');
}

上述脚本总是在我的控制台中返回“时间二错误”。我还尝试将“time_two”的值设置为“00:00”,但仍无法验证。
我的正则表达式有问题吗?
注意:我也尝试了以下正则表达式,但效果相同。
var timeFormat      =    /(\d{2}\:\d{2})/g;

感谢大家的回复!! :) - KodeFor.Me
4个回答

11
我认为这是来自于“global”标志,尝试使用以下代码替代:
var timeFormat = /^([0-9]{2})\:([0-9]{2})$/;

请参见以下链接:https://dev59.com/gnI_5IYBdhLWcg3wHfOr - alecxe
1
是的,也尝试使用/^\d\d:\d\d$/ - elclanrs
1
@wared 谢谢你的回答,那就是问题所在,现在正常工作了。我会在不到10秒钟内为你的回答点赞 :) - KodeFor.Me
回答不错,但会允许无效的时间值,例如99:99。 - Michael L.

1

test会将全局正则表达式向前匹配一次,并在到达字符串末尾时倒回。

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

所以你需要在场景中去掉g标志。

@Amadan 你是FlashFrance的成员,对吧? :-) - user1636522

1
我可以提出以下选项:
/^[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

0

简单易懂

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

输出:

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

演示:https://regexr.com/40vuj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接