时间格式的 JavaScript 正则表达式验证问题
JavaScript regex validation issue with time format
我尝试使用以下脚本验证时间瓦利,但由于某种原因,第二个值没有验证。我的脚本有什么问题吗?
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
相关文章:
- Javascript验证问题
- CRM身份验证问题
- 获取json结果的身份验证问题
- JS表单验证问题
- 如何在窗体中使用多个按钮解决验证问题
- 带有jquery验证问题的php表单
- Google UiApp中的Google Apps脚本验证问题
- 骨干模型验证问题
- IPV6验证问题
- PHP表单,MailFoction和Google reCaptcha验证问题
- 我在登录页面上遇到php验证问题
- jQuery,CORS,JSON(不带填充)和身份验证问题
- JQuery 使用引导 col-x 时验证问题
- 如何清除两个提交按钮的验证问题
- Facebook标签/页面身份验证问题:getLoginStatus总是返回not_authorized
- asp.net JavaScript 验证问题
- 主干验证问题
- 表单验证问题(Javascript)
- jquery ajax 调用表单身份验证问题
- 指令中的角度验证问题