I use timepicker for my start and end time. I would like to have validation on these two input fields in case if user enter wrong time format. Here is my HTML code:
<th>Start Time:</th>
<td>
<input type="text" id="stime" name="stime" maxlength="10"/>
</td>
<th>End Time:</th>
<td>
<input type="text" id="etime" name="etime" maxlength="10"/>
</td>
Here is my JavaScript validation code:
var sTime = $('#stime').val();
var eTime = $('#etime').val();
var regExp = /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/i
if(regExp.test(sTime) == false){
alert('Start Time is wrong');
}else if(regExp.test(eTime) == false){
alert('End Time is wrong');
}
My code does not work, If I pick correct time format in my timepicker I will get alert that time is wrong. If anyone can help with this problem please let me know. My time values look like this:
start time: 08:00 am
end time: 01:15 pm
If you want to match the time intervals splitted in am and pm the time range will be between 00:00 and 12:59.
So your regex will be:
^(?:(?:0?\d|1[0-2]):[0-5]\d)$
Check the online demo
Legenda
^ # Start of the string
(?: # NCG1
(?: # NCG2
0?\d # An optional zero followed by a single number between zero and nine \d is just like [0-9]
| # OR
1[0-2] # A literal '1' followed by a single number between zero and two
) # CLOSE NCG2
: # A literal colon ':'
[0-5]\d # A single number from 0 to 5 followed by any digit
) # CLOSE NCG1
$ # End of the string
Js Demo
var re = /^(?:(?:0?\d|1[0-2]):[0-5]\d)$/;
var tests = ['08:00','01:15','1:14','02:23','23:23','12:01','13:05','3:04','5:65','0:0','12:9','0:34','0:01','00:31','0:00','00:00'];
var m;
while(t = tests.pop()) {
document.getElementById("r").innerHTML += '"' + t + '"<br/>';
document.getElementById("r").innerHTML += 'Valid time? ' + ( (t.match(re)) ? '<font color="green">YES</font>' : '<font color="red">NO</font>') + '<br/><br/>';
}
<div id="r"/>
Update: i've modified the regex to discard some values accepted before such like the weird 0:0 or 12:9 (depending on the single digit minute section), as suggested by Mic in the comment.
However the regex continues to match the minutes after midnight 00:xx and noon 12:xx. In the italian digital clocks this is just the way used to distinguish on the fly between zenith and nadir (i can't be sure it's universally accepted but i think it's a reasonable default).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With