Reputation: 2029
I have a field which should take input in format HH:MM (it can be 00:01
, 01:19
, 25:00
, 99:34
, 123:12
)
So before submitting the form I need to check whether the value is in any of the above formats else throw an error message .
The field:
<input type="text" value="" name="totalDuration" id="total_duration" class="" />
Validation code goes here
function validate(){
var totalDuration = $("#total_duration").val();
// Rest of the code which checks value is in given format
}
Upvotes: 3
Views: 3367
Reputation: 402
If someone needs 00:00 - 23:59 range:
function validate(){
var totalDuration = $("#total_duration").val();
return /^([2][0-3]:[0-5][0-9])|([0-1][0-9]:[0-5][0-9])$/.test(totalDuration);
}
Range 01:00 - 12:59:
function validate(){
var totalDuration = $("#total_duration").val();
return /^([1][0-2]:[0-5][0-9])|([0][1-9]:[0-5][0-9])$/.test(totalDuration);
}
Upvotes: 0
Reputation: 75317
You could do;
function validate(){
var totalDuration = $("#total_duration").val();
return /^\d{2}:\d{2}$/.test(totalDuration);
}
this is a regular expression which checks for 2 digits followed by a ":" followed by 2 more digits. It could be more precise (i.e. checking for <24 hours and <60 minutes)
If you want to check for at least 2 hour digits (to accept 123:12 per your example), try the regular expression /^\d{2,}:\d{2}$/
To check for two or three hour digits, do; /^\d{2,3}:\d{2}$/
Upvotes: 4