Jquery - Validating time value on a form - correct way?

瘦欲@ 提交于 2019-12-09 15:37:51

问题


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.


回答1:


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

Fiddle

Documentation.

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" />

Fiddle

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

Demo




回答2:


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".




回答3:


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.



来源:https://stackoverflow.com/questions/12029111/jquery-validating-time-value-on-a-form-correct-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!