Reputation: 370
I have a form with <input type="time">
were I want it to validate based on a specific timeframe, e.g. it should only validate between 08:00 and 22:00.
I have tried using the min / max values, but that doesn't work for validation...
<input type="time" min="0800" max="2200" required>
I'm using the jQuery Validation Plugin.
Any tips on how I can accomplish this and if its even possible?
Check out this JSFiddle to see what I'm trying to accomplish.
Thanks :)
Upvotes: 0
Views: 5515
Reputation: 1371
You can add a custom validator, something like:
jQuery.validator.addMethod("timey", function(value, element) {
var hour = parseInt(value.substring(0,2));
return hour > 7 && hour < 23;
}, "Invalid time");
Then apply that to your field. Be careful about field names, though- it looks like the JSFiddle you posted isn't set up properly.
Setting up the min and max properly (min="08:00:00" max="22:00:00"
) is more elegant, but the validator doesn't seem to handle the edge cases properly, rejecting exactly 8:00 and 22:00.
Upvotes: 2
Reputation: 2021
First of all as stated here the min/max attributes should be formatted as datetime values like min="08:00:00"
and max="22:00:00"
.
For jQuery validation, take a look here:
date: function( value, element ) {
return this.optional(element) || !/Invalid|NaN/.test(new Date(value).toString());
},
and for time validation within the given input string:
$.validator.addMethod("time", function (value, element) {
return this.optional(element) || /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/i.test(value);
}, "Please enter a valid time.");
Upvotes: 0