Reputation: 716
I'm looking for a regex string for validating time.
I validate my HTML form using ^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$
which works great however I wish to create some sort of input mask for time entry on my HTML text input field which I'll attach to a keydown
event to test the input as the user types.
Accepted Values
Upvotes: 0
Views: 3942
Reputation: 152
Input mask for time with partial check
<input type="text" id="timeinput" name="time" value="" onkeyup="validateTime(this);"/>
<span id="validationresult"></span>
<script>
function validateTime(el)
{
var result;
// first, check if input is fully correct
if (el.value.match(/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/))
result = "OK";
// then, check if it is not wrong
else if (el.value.match(/^([0-9]|0[0-9]|1[0-9]|2[0-3])?(:([0-5]|[0-5][0-9])?)?$/))
result=""; // don't bother user with excess messages
else
result="Please, correct your input";
document.getElementById("validationresult").innerHTML=result;
}
</script>
Feel free to optimize extra match, but here you can see difference between 2 expressions.
Upvotes: 2