Reputation: 153
After google searching, searching this site as well as jQuery found there was no easy way to validate time value.
By the looks of things it suggest using addMethod and use the to regexpess the value to check against what time should look like.
However decided to look at the jquery.validate.js
and how dateISO was checked, it looked lot easier way to do it, so I then copied all data relating to dateISO and called it timeISO and changed the string to validate time and used the following time sting
^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$
Is there some reason why one should not modify jquery.validate.js
and do it the way I have? Just a little bit worried as all my searching on google and this forum it was never suggested.
Upvotes: 9
Views: 34600
Reputation: 854
I know it's been a while, but I think the best solution is to check the additional-methods.js library. (You can download it from http://jqueryvalidation.org/)
There are two validations: "time12h" and "time".
Upvotes: 4
Reputation: 70139
You can add custom methods to jQuery.validate
. There's probably one available for this but I coded this 24h time format validation as an example:
$.validator.addMethod("time24", function(value, element) {
if (!/^\d{2}:\d{2}:\d{2}$/.test(value)) return false;
var parts = value.split(':');
if (parts[0] > 23 || parts[1] > 59 || parts[2] > 59) return false;
return true;
}, "Invalid time format.");
You can also sum it up in a single regular expression (source):
([01]?[0-9]|2[0-3])(:[0-5][0-9]){2}
And if you're using HTML5, you can use the pattern
attribute:
<input type="text" pattern="([01]?[0-9]|2[0-3])(:[0-5][0-9]){2}"
required="required" placeholder="hh:mm:ss" />
Keep using the jQuery.validate
method if you need compatibility with older browsers though:
$.validator.addMethod("time24", function(value, element) {
return /^([01]?[0-9]|2[0-3])(:[0-5][0-9]){2}$/.test(value);
}, "Invalid time format.");
Upvotes: 17
Reputation: 33865
Modifying the plugin core makes it more difficult to update to a new version of the plugin, without replacing your modifications, and is rarely a good idea.
I'd suggest that you place your custom code in a separate file, instead of altering the core code.
Upvotes: 1