如何使用验证插件 jquery 验证输入数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24670447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:38:24  来源:igfitidea点击:

How to validate array of inputs using validate plugin jquery

jqueryjquery-validate

提问by Amit

Am new to jquery validation plugin but i would like to know how do we validate array of input boxes using validation plugin..

我是 jquery 验证插件的新手,但我想知道我们如何使用验证插件验证输入框数组。

Below is html code.

下面是html代码。

<form id="transport-form">
  <input type="text" name="qty[]" id="qty1">
  <input type="text" name="qty[]" id="qty2" >
  <input type="text" name="qty[]" id="qty3">
  <input type="text" name="qty[]" id="qty4">
  <input type="submit value="submit">
</form>

and jquery code is below

和 jquery 代码在下面

jQuery("#transport-form").validate({
        rules: {
            'qty[]': {
                required: true
            }
        },
    });

But everytime i click submit it is validating only the first value. rest all the values of same name are not validated. Please help.

但每次我点击提交时,它只验证第一个值。其余的所有同名值都不会被验证。请帮忙。

回答by Amit

Sometimes we need to validate an array of input elements: For example –

有时我们需要验证输入元素数组:例如 –

<form name="signupForm" class="cmxform" id="signupForm" method="get" action="">
    <select name="category[]" id="cat_1">
    <option value="">Select One</option>
    <option value="1">aa</option>
    <option value="2">bb</option>
    <option value="3">cc</option>
    <option value="4">dd</option>
    </select>

    <select name="category[]" id="cat_2">
    <option value="">Select One</option>
    <option value="5">ee</option>
    <option value="6">ff</option>
    <option value="7">gg</option>
    <option value="8">hh</option>
    </select>

    <select name="category[]" id="cat_3">
    <option value="">Select One</option>
    <option value="9">ii</option>
    <option value="10">jj</option>
    <option value="11">kk</option>
    <option value="12">ll</option>
    </select>

    <input class="submit" type="submit" value="Submit">
    </form>

Now we will use jquery validation plugin jquery.validate.js for validating the form. The condition will be that user will have to choose category from each dropdown. The script for validation will be as below -

现在我们将使用 jquery 验证插件 jquery.validate.js 来验证表单。条件是用户必须从每个下拉列表中选择类别。验证脚本如下 -

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.validate.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
    // validate the comment form when it is submitted
    $("#signupForm").validate({
        rules: {
            "category[]": "required"
        },
        messages: {
            "category[]": "Please select category",
        }
    });
});
</script>

Now the problem is that the readymade jquery.validate.js only validates the first element of category[]. So, we need to modify it a little bit.

现在的问题是现成的 jquery.validate.js 只验证 category[] 的第一个元素。所以,我们需要稍微修改一下。

In jquery.validate.js, we can find a function named checkForm, we have to modify it as below:

在 jquery.validate.js 中,我们可以找到一个名为 checkForm 的函数,我们需要修改它如下:

checkForm: function() {
    this.prepareForm();
    for (var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++) {
        if (this.findByName(elements[i].name).length != undefined && this.findByName(elements[i].name).length > 1) {
            for (var cnt = 0; cnt < this.findByName(elements[i].name).length; cnt++) {
                this.check(this.findByName(elements[i].name)[cnt]);
            }
        } else {
            this.check(elements[i]);
        }
    }
    return this.valid();
}

I just got this solution from http://www.codeboss.in/web-funda/2009/05/27/jquery-validation-for-array-of-input-elements/hope this helps someone..

我刚从http://www.codeboss.in/web-funda/2009/05/27/jquery-validation-for-array-of-input-elements/得到这个解决方案希望这对某人有帮助..

回答by Christo

You can pass an option in to ignore part of a field name; As for the original posts comments, there are plenty of use-cases for having a name[] style name in HTML, especially using PHP.

您可以传入一个选项来忽略部分字段名称;至于原始帖子评论,有很多用例可以在 HTML 中使用 name[] 样式名称,尤其是使用 PHP。

$("#my-form").validate({
  submitHandler: function(form) {
    form.submit();
  },
  ignore: [],
  rules: {
    'category[]': {
      required: true
    }
  }
});

回答by Quinten

I noticed that the jQuery validate plugin i use will only detect the first element with a specific name.

我注意到我使用的 jQuery 验证插件只会检测具有特定名称的第一个元素。

Another way to make the jQuery validate plugin also detect all the inputs beyond the first could be by making the names unique. So you could replace:

另一种使 jQuery 验证插件也检测除第一个之外的所有输入的方法是使名称唯一。所以你可以替换:

<input type="text" name="qty[]" />
<input type="text" name="qty[]" />
<input type="text" name="qty[]" />
<input type="text" name="qty[]" />

with:

和:

<input type="text" name="qty[0]" />
<input type="text" name="qty[1]" />
<input type="text" name="qty[2]" />
<input type="text" name="qty[3]" />

回答by Chris Sim

This is the Best solution I found and I'am currently using in my project:

这是我找到的最佳解决方案,我目前在我的项目中使用:

// Adding rule to each item in qtyi list 
jQuery('[id^=qty]').each(function(e) {
    jQuery(this).rules('add', {
        minlength: 2,
        required: true
    });
});

回答by Eva M

First, for jQuery to distinguish between the elements you need to have a different id per element. This can be done programmatically when you add the inputs. Then what you need to do is to verify all inputs with common name at once. For that, create a custom validator using the addMethod() function as described in the documentation

首先,为了让 jQuery 区分元素,您需要为每个元素设置不同的 id。这可以在您添加输入时以编程方式完成。然后您需要做的是一次验证所有具有通用名称的输入。为此,使用文档中所述的 addMethod() 函数创建自定义验证器

jQuery.validator.addMethod("allRequired", function(value, elem){
        // Use the name to get all the inputs and verify them
        var name = elem.name;
        return  $('input[name="'+name+'"]').map(function(i,obj){return $(obj).val();}).get().every(function(v){ return v; });
    });

You can use this as a rule on your array elements :

您可以将其用作数组元素的规则:

$('form').validate(
        {
         rules: { 
               "nbPieces[]": "allRequired"
         },

         submitHandler : function(form, event) {
              event.preventDefault();   
              //... etc
         }
});

For the errors to appear correctly on the empty fields though, you may need to override the errorPlacement option from validate...

但是,为了让错误在空字段上正确显示,您可能需要覆盖 validate... 中的 errorPlacement 选项。

回答by Ajay Patidar

You need to make indexing of each elements

您需要对每个元素进行索引

Below is html code.

下面是html代码。

<form id="transport-form">
  <input type="text" name="qty[0]" id="qty1">
  <input type="text" name="qty[1]" id="qty2" >
  <input type="text" name="qty[2]" id="qty3">
  <input type="text" name="qty[3]" id="qty4">
  <input type="submit value="submit">
</form>

and jquery code is below

和 jquery 代码在下面

jQuery("#transport-form").validate({
    rules: {
        'qty[]': {
            required: true
        }
    },
});

回答by shankit

Here the solution without giving indexing to array.

这里的解决方案没有给数组提供索引。

<form>
    <div>Name:
       <p>
        <input name="name_ct[]" id="id_ct0" type="text" class="form-control" placeholder="Add Variant 1 Name">
        </p>
    </div>
    <input type="button" value="Add Variant" />
    <input type="submit" />
</form>

js Code

js代码

$(document).ready(function () {
 $.validator.addMethod("mytst", function (value, element) {
        var flag = true;

      $("[name^=name_ct]").each(function (i, j) {
                        $(this).parent('p').find('label.error').remove();
$(this).parent('p').find('label.error').remove();                        
                        if ($.trim($(this).val()) == '') {
                            flag = false;

                            $(this).parent('p').append('<label  id="id_ct'+i+'-error" class="error">This field is required.</label>');
                        }
                    });


                    return flag;


    }, "");
$("form").validate({

    ignore: '',
    rules: {
        "name_ct[]": {
            mytst:true
        }
    },
    submitHandler: function () {
        //you can add code here to recombine the variants into one value if you like, before doing a $.post
         form.submit();
        alert('successful submit');
        return false;
    }
});

var j = 1;
$('input[type="button"]').click(function () {
    $('form div').append('<p><input name="name_ct[]" id="id_ct' + j + '" type="text" class="form-control" placeholder="Add Variant ' + j + ' Name " ></p>');

    j++;
});
});

you can see here in js fiddle: https://jsfiddle.net/q0d76aqx/42/

你可以在 js fiddle 中看到:https: //jsfiddle.net/q0d76aqx/42/

回答by Pavel

I've used solution proposed by AsgarAli Khanusiya but JQuery.Validator shows label with error message in same cases in the wrong place. It happens because it stores previously shown messages. If user make same mistake with different item in the collection then validator displays label in the previous place instead of generation new label near element with issue. I've overrided 'errorsFor' method to solve this:

我使用了 AsgarAli Khanusiya 提出的解决方案,但 JQuery.Validator 在错误的地方在相同的情况下显示带有错误消息的标签。发生这种情况是因为它存储了先前显示的消息。如果用户对集合中的不同项目犯同样的错误,则验证器会在前一个位置显示标签,而不是在有问题的元素附近生成新标签。我已经覆盖了 'errorsFor' 方法来解决这个问题:

$.validator.prototype.errorsFor = function (element) {
    var name = this.idOrName(element);
    var elementParent = element.parentElement;
    return this.errors().filter(function() {
        return $(this).attr('for') == name && $(this).parent().is(elementParent);
    });
}

回答by Ravindra Bohra

jQuery Form Validator is a feature rich and multilingual jQuery plugin that makes it easy to validate user input while keeping your HTML markup clean from javascript code. Even though this plugin has a wide range of validation functions it's designed to require as little jQuery network traffic as possible. This is achieved by grouping together validation functions in "modules", making it possible to load only those functions that's needed to validate a particular form.

jQuery Form Validator 是一个功能丰富的多语言 jQuery 插件,它可以轻松验证用户输入,同时保持 HTML 标记与 javascript 代码的清洁。尽管此插件具有广泛的验证功能,但它的设计目的是尽可能少地使用 jQuery 网络流量。这是通过将“模块”中的验证功能组合在一起来实现的,从而可以仅加载验证特定表单所需的那些功能。

<form action="" id="registration-form">
  <p>
    E-mail
    <input name="email" data-validation="email">
  </p>
  <p>
    User name
    <input name="user" data-validation="length alphanumeric" 
         data-validation-length="3-12" 
         data-validation-error-msg="User name has to be an alphanumeric value (3-12 chars)">
  </p>
  <p>
    Password
    <input name="pass_confirmation" data-validation="strength" 
         data-validation-strength="2">
  </p>
  <p>
    Repeat password
    <input name="pass" data-validation="confirmation">
  </p>
  <p>
    Birth date
    <input name="birth" data-validation="birthdate" 
         data-validation-help="yyyy-mm-dd">
  </p>
  <p>
    Country
    <input name="country" id="country" data-validation="country">
  </p>
  <p>
    Profile image
    <input name="image" type="file" data-validation="mime size required" 
         data-validation-allowing="jpg, png" 
         data-validation-max-size="300kb" 
         data-validation-error-msg-required="No image selected">
  </p>
  <p>
    User Presentation (<span id="pres-max-length">100</span> characters left)
    <textarea name="presentation" id="presentation"></textarea>
  </p>
  <p>
    <input type="checkbox" data-validation="required" 
         data-validation-error-msg="You have to agree to our terms">
    I agree to the <a href="..." target="_blank">terms of service</a>
  </p>
  <p>
    <input type="submit" value="Validate">
    <input type="reset" value="Reset form">
  </p>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
<script>

  $.validate({
    modules : 'location, date, security, file',
    onModulesLoaded : function() {
      $('#country').suggestCountry();
    }
  });

  // Restrict presentation length
  $('#presentation').restrictLength( $('#pres-max-length') );

</script>
...