如何使用 jquery-validate 验证数组输入

how to validate array input using jquery-validate

我有一个数组输入字段,我正在尝试使用 jquery 验证,但它不起作用。 http://jsfiddle.net/shorif2000/hfrhs/196/

可以有多个以下输入字段。

<form name="frmCreateCM" id="frmCreateCM" method="post" accept-charset="utf-8" class="form-horizontal">
    <input size="15" maxlength="20" name="src[0]" class="form-control">
    <input size="15" maxlength="20" name="src[1]" class="form-control">
    <input size="15" maxlength="20" name="src[2]" class="form-control">
    <input size="15" maxlength="20" name="src[3]" class="form-control">
</form>

$.extend( $.validator.prototype, {
    checkForm: function () {
        this.prepareForm();
        console.log(this);
        for (var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++) {
            console.log(elements[i].name);
            console.log(this.findByName(elements[i].name).length);
            console.log(elements[i]);
            //if (this.findByName(elements[i].name).length != undefined && this.findByName(elements[i].name).length > 1) {
            if(true){
                console.log(this.findByName(elements[i].name));
                for (var cnt = 0; cnt < this.findByName(elements[i].name).length; cnt++) {
                    console.log(this.findByName(elements[i].name)[cnt]);
                    this.check(this.findByName(elements[i].name)[cnt]);
                }
            } else {
                var el = this.findByName(elements[i].name);
                this.check(elements[i]);
            }
        }
        return this.valid();
    }
});
$("form[name='frmCreateCM']").validate({

        rules: {
            "src[]" : {
                required: true
            },
            "srcport[]" : {
                required: true
                },
            "dst[]" : {
                required: true
                },
            "dstport[]" : {
                required: true
                }
        },
        showErrors: function(errorMap, errorList) {
            console.log(errorMap);
            console.log(errorList);
            $.each( this.successList , function(index, value) {
                $(value).popover('hide');
            });
            $.each( errorList , function(index, value) {

                 var _popover = $(value.element).popover({
                    trigger: 'manual',
                    placement: 'top',
                    content: value.message,
                    template: '<div class="popover"><div class="arrow"></div><div class="popover-inner"><div class="popover-content"></div></div></div>'
                });
                 _popover.data('bs.popover').options.content = value.message;
                 $(value.element).popover('show');
            });
        },
        submitHandler: function (form) {
        //submit(function(e){
            //e.preventDefault();
            //fix timer
            $("#addRow").addClass('disabled');
            $("#btnCreateCM").css('width','110px');
            $("#btnCreateCM").css('background','#aaaaaa');
            $("#btnCreateCM").css('border','1px solid #676767');
            startTimer('btnCreateCM');
            document.getElementById("btnCreateCM").disabled = true;

            var formdata = $('form').serialize();
            formdata += "&csrf="+$.csrfParam('csrf') ;
            $.post('/api/admin/add/comms/matrices/format/json/',formdata, function( msg ) {
                stopTimer();
                if(msg.header.error){
                    $("#myModalError .modal-body").html(msg.header.message);
                    $("#myModalError").modal('show');
                }else{
                    $("#view_comms_matrix").attr('href','/api/user/commsmatrix/id/'+msg.body.recordset.record.comms_matrix_id+'/format/xml?csrf='+$.csrfParam('csrf'));

                    var html = '<table class="table table-striped table-bordered table-hover table-condensed">'+
                    '<tr><td>Analysis Start</td><td>'+msg.header.metadata.analysis_start+'</td></tr>'+
                    '<tr><td>Analysis End</td><td>'+msg.header.metadata.analysis_end+'</td></tr>'+
                    '<tr><td>Analysis Time</td><td>'+msg.header.metadata.analysis_time+'</td></tr>'+
                    '<tr><td>Upload Status</td><td>'+msg.header.upload_status+'</td></tr>';
                    if(msg.header.error_flows > 0){
                        html += '<tr><td style="width: 120px; vertical-align: text-top; font-size: 14px; border-right: 1px solid #aaaaaa; border-bottom: 1px solid #aaaaaa; padding-right: 25px; color: #ef0000;">Row Input Errors</td><td style="font-size: 14px; border-right: 1px solid #aaaaaa; border-bottom: 1px solid #aaaaaa; padding-right: 25px; color: #ef0000;">'+msg.header.error_flows+'</td></tr>';
                    }
                    html += '</table>';

                    $('#myModalCreate .modal-body').html(html);
                    ga('send', 'event', 'Comms Matrices', 'Create', msg.body.recordset.record.comms_matrix_id);

                    $("#myModalCreate").modal('show');
                }
            });
        //});
        }
    });

我已尝试遵循此 post How to validate array of inputs using validate plugin jquery 但它不起作用。

你不能像你在这里尝试的那样做...

$("form[name='frmCreateCM']").validate({
    ....
    rules: {
        'reg_number[*]': {
         ....

没有在 JavaScript 变量中插入 * 作为通配符这样的事情。

为了使声明规则的过程不那么繁琐,您可以使用 jQuery .each() 结合此插件的 .rules() 方法。 Select 所有 name 属性 "starting with" reg_number...

$('[name^="reg_number"]').each(function() {
    $(this).rules('add', {
        required: true,
        minlength: 2,
        messages: {
            required: "Enter Reg Number",
            minlength: "Enter at least {0} characters",
        }
    })
});

演示:jsfiddle.net/43b19sq3/

注意:

除了复选框和单选框组之外,您不能使用此插件在 form 中的多个元素上使用相同的 name。换句话说,您不能在多个元素上使用 reg[]。但是可以使用一个索引号,有reg[0]reg[1]

Markup Recommendations in the docs:

"Mandated: A 'name' attribute is required for all input elements needing validation, and the plugin will not work without this. A 'name' attribute must also be unique to the form, as this is how the plugin keeps track of all input elements. However, each group of radio or checkbox elements will share the same 'name' since the value of this grouping represents a single piece of the form data."