【问题标题】:JavaScript regex validation issue with time format时间格式的 JavaScript 正则表达式验证问题
【发布时间】:2013-09-11 08:24:07
【问题描述】:

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

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;

【问题讨论】:

  • 感谢大家的回复!! :)

标签: javascript regex validation


【解决方案1】:

我认为它来自“全局”标志,试试这个:

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

【讨论】:

  • 是的,也可以试试/^\d\d:\d\d$/
  • @wared 感谢您的回答,这就是问题所在,现在可以正常工作了。我会在
  • 不错的答案,但允许使用无效的时间值,例如 99:99。
【解决方案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 标志。

【讨论】:

  • @Amadan 你是 FlashFrance 的成员吧? :-)
【解决方案3】:

我可以提出以下选择吗:

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

【讨论】:

    【解决方案4】:

    简单的

    /^([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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-14
      • 2014-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      • 2011-10-06
      相关资源
      最近更新 更多