jQuery-在表单上验证时间值-正确的方法?

问题描述:

在google搜索之后,搜索此网站以及 jQuery 发现,没有简单的方法可以验证时间值.

After google searching, searching this site as well as jQuery found there was no easy way to validate time value.

通过外观建议使用 addMethod 并使用regexpess检查时间应该是什么样的值.

By the looks of things it suggest using addMethod and use the to regexpess the value to check against what time should look like.

无论如何决定查看jquery.validate.js以及如何检查dateISO,它看起来很简单,因此我复制了所有与dateISO有关的数据,并将其命名为timeISO,并更改了字符串以验证时间并使用了接下来的时间

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$ 

有人出于某种原因不应该修改jquery.validate.js并按照我的方式进行操作吗?只是有点担心,因为我在Google和这个论坛上进行的所有搜索都从未被建议过.

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.

您可以将自定义方法添加到jQuery.validate.可能有一个可用的方法,但我以24小时格式验证为例进行了编码:

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}

如果您使用的是HTML5,则可以使用pattern属性:

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

小提琴

但是,如果您需要与旧版浏览器兼容,请使用jQuery.validate方法:

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

演示