Javascript RegEx:验证时间 [英] Javascript RegEx: validate time

查看:94
本文介绍了Javascript RegEx:验证时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个秒表变量可以按以下格式获取值:
HH:MM:SS 大部分时间。 'HH'可以超过24小时 - 基本上是任何有效数字。

I have a stopwatch variable that can get value in the following format: HH:MM:SS most of the time. 'HH' can go past 24 hours - basically any valid number.

我对这个正则表达式的东西并不是那么好,但是能够写出一些对大多数情况有益的东西但却无法验证小时是否为单位数。防爆。低于正则表达式时间 1:10:09 ,但它无效。有效小时部分应为 01

I am not that good with this regex thingy, but was able to write something that is good for most part but fails to validate if the hour is single digit. Ex. below regex pass the time 1:10:09, though it is invalid. valid hour part should be 01.

//var stopWatchTime = '02:10:09'; //Valid
//var stopWatchTime = '00:10:09'; //Valid
//var stopWatchTime = '1234:10:09'; //Valid
//var stopWatchTime = ':10:09'; //Invalid
//var stopWatchTime = 'ax:10:09'; //Invalid
var stopWatchTime = '1:10:09'; //Invalid, should be 01:10:09. 

if(!stopWatchTime .match(/^\d+:\d{2}:\d{2}$/)){
    alert('invalid time- ' + stopWatchTime);
}
else{
    alert('valid time - ' + stopWatchTime);
}

我应该在正则表达式中更改它应该检查任何数字但是小时部分应该有2位数还是更多?

What should I change in the regex to say it should check for any number but should have 2 digits or more in hour part?

推荐答案

/^\d{2,}:\d{2}:\d{2}$/

更改+到{2,}允许它有两个或多个字符

Change the + to a {2,} to allow it to have two or more characters

如果你想看到匹配和不匹配的东西你可以玩它这里 http://regexr.com?31fu4

If you want to see the things that matches and doesn't match you can play with it here http://regexr.com?31fu4

编辑:
此外,如果您只想在小时/分钟内匹配最多59个部分使用

Also if you only want to match up to 59 in the hours/minutes part use

^\d{2,}:(?:[0-5]\d):(?:[0-5]\d)$

这篇关于Javascript RegEx:验证时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆