JQuery - Checking the time value on a form - the right way?

After searching on Google, searching on this site, as well as jQuery , there was no easy way to check the time value.

For reasons suggested by addMethod , use the regexpess value to check what time should look like.

However, I decided to look at jquery.validate.js and how jquery.validate.js was checked, it looked a lot easier, so I copied all the data related to dateISO and called it timeISO and changed the line to check the time and used it after time

 ^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$ 

Is there any reason why you can't modify jquery.validate.js and do it the way I do? Just a little worried, since all my searches on google and this forum have never been offered.

+7
source share
3 answers

You can add your own methods to jQuery.validate . Probably one of them is available for this, but as an example, I encoded this check in a 24-hour format:

 $.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."); 

Fiddle

Documentation

You can also sum it in one regular expression ( source ):

 ([01]?[0-9]|2[0-3])(:[0-5][0-9]){2} 

And if you use 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" /> 

Fiddle

Continue to use the jQuery.validate method if you need compatibility with older browsers:

 $.validator.addMethod("time24", function(value, element) { return /^([01]?[0-9]|2[0-3])(:[0-5][0-9]){2}$/.test(value); }, "Invalid time format."); 

Demo

+11
source

I know that this has been a while, but I believe that the best solution is to check the extra-methods.js library. (You can download it from http://jqueryvalidation.org/ )

There are two checks: "time12h" and "time .

+2
source

Changing the plugin core makes it difficult to upgrade to a new version of the plugin without replacing your modifications and is rarely a good idea.

I would suggest that you put your own code in a separate file instead of modifying the kernel code.

+1
source

All Articles