Reputation: 4298
I want to validate the time duration, It should be in HH:MM:SS format. How should I do the validation for this.Is there some plugin which can be used for this purpose or I need to use JS validation.
Time Duration <input type="text" name="time_duration" value="00:00:00"><br>
Upvotes: 1
Views: 2554
Reputation: 737
This is e dead simple regexp you can use to validate your input as HH:MM:SS
format:
^([0-2][0-3]):([0-5][0-9]):([0-5][0-9])$
The explanation is really easy, 3 groups of 2 character separated by :
each character must be a digit contained in that specific ranges.
You can customize it to be less restrictive.
var regexp = new RegExp(/^([0-2][0-3]):([0-5][0-9]):([0-5][0-9])$/)
regexp.test("14:20:05") // true
regexp.test("14:20:70") // false (invalid seconds)
regexp.test("25:20:00") // false (invalid hours)
regexp.test("14-30-00") // false (invalid separator)
Here an example of validation using jquery on blur event (when the input loses focus):
$(document).ready(function() {
$('input').blur(function() {
var value = $(this).val();
if (isValidTime(value))
$(this).css('background','green');
else
$(this).css('background','red');
})
function isValidTime(text) {
var regexp = new RegExp(/^([0-2][0-3]):([0-5][0-9]):([0-5][0-9])$/)
return regexp.test(text);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
Upvotes: 2
Reputation: 7838
Instead of a text input, why not use 3 select boxes that you fill out with the correct time values? That way, you don't have to validate the user input at all, as you can force the user to give a time in your preferred format. Throw some nice CSS at it and you have a very clean looking solution.
<label>Hours</label>
<select name="hours">
<option value="0">0</option>
//repeat 23 more times
</select>
<label>Minutes</label>
<select name="minutes">
<option value="0">0</option>
<option value="1">1</option>
//repeat 59 more times
</select>
<label>Seconds</label>
<select name="seconds">
<option value="1">1</option>
//repeat 59 more times
</select>
The downside: you have a lot of extra HTML. The upside: it requires less JavaScript validation to do this, you only need to validate server side that hours is in the 0-23 range, and that minutes and seconds are in the 0-59 range, in case the client sends weird info your way.
Upvotes: 1