Reputation: 6928
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" />
Upvotes: 3
Views: 28365
Reputation: 255
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.
Upvotes: 6
Reputation: 5532
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.
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;
}
Upvotes: 0
Reputation: 22637
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.
Upvotes: 3
Reputation: 147483
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.
Upvotes: 2
Reputation: 8348
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);
Upvotes: 9