0

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

  • 1
  • 12
  • 12:
  • 12:5
  • 12:59
Robula
  • 649
  • 1
  • 12
  • 29
  • 2
    Maybe try google? - http://stackoverflow.com/questions/7536755/regular-expression-for-matching-hhmm-time-format – Styphon Mar 21 '14 at 16:02
  • How is anything other than `^(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$` a valid time? – tenub Mar 21 '14 at 16:11

1 Answers1

2

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.

NekoNaz
  • 181
  • 6
  • Thank you. This is what I'm doing already and it works. I just wondered if it were possible to validate as I type. By that I mean `result` shouldn't show "wrong" if the user has begun to type `12` but should show "wrong" if the user has begun to type `9` or `24` as neither of these are valid hours etc... Is this possible via Regex? Thanks – Robula Mar 27 '14 at 13:26
  • Edited my code. I think you can adjust it to your needs. – NekoNaz Mar 27 '14 at 13:59
  • `^([0-9]|0[0-9]|1[0-9]|2[0-3])?(:([0-5]|[0-5][0-9])?)?$` This is EXACTLY what I was after! Thank you so much!! :) I wish I could understand it, but at least it works. Thanks NekoNaz – Robula Mar 27 '14 at 14:27