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

JavaScript regex validation issue with time format

本文关键字:验证 问题 正则表达式 JavaScript 格式 时间      更新时间:2023-09-26

我尝试使用以下脚本验证时间瓦利,但由于某种原因,第二个值没有验证。我的脚本有什么问题吗?

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;

我认为它来自"全局"标志,请尝试以下操作:

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

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 标志。

我可以提出以下选择:

/^[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)$/

输出:

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

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