how to validate 24 hour formated Time in Jquery or javascript?
25,310
Solution 1
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);
Solution 2
A different approach, but using an extra javascript lib:
var valid = moment(timeStr, "HH:mm:ss", true).isValid();
I guess if you already use moment.js in your project, there's no downside.
Solution 3
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.
Solution 4
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.
Author by
Ram Singh
learn learn and learn as much as you can dude..... because learning could never be end up.
Updated on November 03, 2020Comments
-
Ram Singh over 3 years
I want to validate 24 hour formatted Time, Time is in the following format.
HH:MM:SS
How could i go for it. Please help me. My HTMl Code is
<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" />