给定类型的所有输入的jQuery验证

jQuery Validation for all inputs of a given type

本文关键字:输入 jQuery 验证 类型      更新时间:2023-09-26

我正在尝试编写一个JavaScript函数,该函数将涵盖type="time"的所有input元素的验证。我正在查看jQueryValidate的文档,但我只找到验证绑定在idname属性上的示例。有办法在全球范围内做到这一点吗?

我想确保时间总是采用hh:mm格式。我找到了一个函数来验证我的时间(见下文)。当这个函数返回false时,我会调用addError()函数在表单中添加一个错误。我不知道该怎么做。

// Check is the input is a valid time
function formatTime(time) {
    var result = false, m;
    var re = /^'s*([01]?'d|2[0-3]):([0-5]'d)'s*$/;
    if ((m = time.match(re))) {
        result = (m[1].length == 2 ? "" : "0") + m[1] + ":" + m[2];
    }
    return result;
}
// Trigger the validation on the onBlur event
$("input[type=time]").blur(function () {
    var value = formatTime($(this).val());
    if (value == false) {
        addError($(this));
    }
});

伊迪丝1:看来我的复制/粘贴技术不是很好。在formatTime()中,如果格式有效,则返回时间;如果格式无效,则返回false

报价OP:

"我正在查看jQuery Validate的文档,但我只是查找验证绑定在idname上的示例所有物有办法在全球范围内做到这一点吗?"

是的。也可以使用.rules('add')方法应用规则,并且该方法可以附加到任何合法的jQuery选择器。要在多个元素上使用此方法,必须将其封装在jQuery .each()方法中。(还要注意,即使您没有使用name属性,每个input也必须包含一个唯一的name。)

$(document).ready(function() {
    $('#myform').validate({  // initialize the plugin on your form
        // any rules and/or options
    });
    $('input[type="time"]').each(function() {
        $(this).rules('add', {
            required: true,
            // another rule, etc.
        });
    });
});

工作演示:http://jsfiddle.net/g8YFa/

有关使用此插件添加规则的完整信息,请参阅此答案。

您想要声明一个自定义验证方法来验证时间格式。

$.validator.addMethod('correctTimeFormat', function (value, element) {
    var result = false, m, regex = /^'s*([01]?'d|2[0-3]):([0-5]'d)'s*$/;
    if (m = value.match(regex)) {
        result = (m[1].length === 2 ? '' : '0') + m[1] + ':' + m[2];
    }
    return result;
}, 'Invalid time format.');

然后,要求对所有输入时间字段使用该自定义验证方法。

$('input[type="time"]').validate({
    rules: {
        value: { correctTimeFormat: true }
    }
});
// Check is the input is a valid time
function formatTime(time) {
    var result = false, m;
    var re = /^'s*([01]?'d|2[0-3]):([0-5]'d)'s*$/;
    if ((m = time.match(re))) {
        //Well it seems like its valid lets return true!  
        return true;
    }else{
       //Well it seems like this is invalid return false!  
        return false;
    } 
}

您必须从formatTime()函数返回值true/false。这样它就会设置在您的"var value=formatTime($(this).val());"声明上!