如何在 Jquery 或 javascript 中验证 24 小时格式的时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11928794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to validate 24 hour formated Time in Jquery or javascript?
提问by Ram Singh
I want to validate 24 hour formatted Time, Time is in the following format.
我想验证 24 小时格式的时间,时间格式如下。
HH:MM:SS
How could i go for it. Please help me. My HTMl Code is
我怎么能去呢。请帮我。我的 HTML 代码是
<asp:TextBox Width="120px" MaxLength="20" ID="txtEndTime" runat="server"></asp:TextBox>
<ajaxctrl:maskededitextender id="metxtEndTime" runat="server" targetcontrolid="txtEndTime"
mask="99:99:99" messagevalidatortip="true" masktype="Number" inputdirection="LeftToRight"
clearmaskonlostfocus="false" acceptnegative="None" errortooltipenabled="True" />
回答by jeff
To only validate the format, you can use this:
要仅验证格式,您可以使用:
var valid = (timeStr.search(/^\d{2}:\d{2}:\d{2}$/) != -1);
If you're trying to validate the values as well, you can try this:
如果您还尝试验证这些值,则可以尝试以下操作:
var valid = (timeStr.search(/^\d{2}:\d{2}:\d{2}$/) != -1) &&
(timeStr.substr(0,2) >= 0 && timeStr.substr(0,2) <= 24) &&
(timeStr.substr(3,2) >= 0 && timeStr.substr(3,2) <= 59) &&
(timeStr.substr(6,2) >= 0 && timeStr.substr(6,2) <= 59);
回答by Jo?o Victor Oliveira
回答by MaxArt
A good pattern for this task would be
这项任务的一个好模式是
/^(?:[01]\d|2[0-3]):(?:[0-5]\d):(?:[0-5]\d)$/.test(document.getElementById("metxtEndTime").value);
That regex could be used in the HTML5 pattern
attribute of input elements, but I didn't try it yet.
那个正则表达式可以用在pattern
input 元素的 HTML5属性中,但我还没有尝试过。
回答by RobG
To validate the format and values:
要验证格式和值:
// Allows times like 24:05:00
function validateTime(s) {
var t = s.split(':');
return /^\d\d:\d\d:\d\d$/.test(s) &&
t[0] >= 0 && t[0] < 25 &&
t[1] >= 0 && t[1] < 60 &&
t[2] >= 0 && t[2] < 60;
}
Depends if you want to allow values like 24:00:00 for midnight and say 24:15:00 as 15 minutes past midnight.
取决于您是否要允许午夜 24:00:00 之类的值,并说 24:15:00 为午夜后 15 分钟。
回答by user462990
This approach is straightforward and accounts for 24:01 as invalid. The "id" is the id in an input statement in the php code so that the colon (:) can be inserted and written back into a time.
这种方法很简单,将 24:01 视为无效。“id”是 php 代码中输入语句中的 id,以便可以插入冒号 (:) 并将其写回时间。
function checkTime(str,id){
if (str.length == 0) return true;
if (str.length < 4) return false;
var x = str.indexOf(":");
if (x < 0){
str = str.substr(0,2)+":"+str.substr(2,2);
document.getElementById(id).value = str;
document.getElementById(id).focus();
return true;
}
if (
(str.substr(0,2) >= 0 ) &&
(str.substr(0,2) <= 24) &&
(str.substr(3,2) >= 0 ) &&
(str.substr(3,2) <= 59) &&
(str.substr(0,2) < 24 || (str.substr(0,2) == 24 && str.substr(3,2) == 0))
)
return true;
return false;
}