简体   繁体   English

用jQuery验证几个输入的最小集合值

[英]Minimum collective value of several inputs with jquery validate

I have several text inputs with the same name and I'm trying to prevent the form from submitting if the collective value of all the inputs is less than 1. Eg the user can't put 0 on all of them, but must at least put 1 on one of them so the collective value of all inputs is at least 1. 我有多个具有相同名称的文本输入,并且如果所有输入的总值小于1,我试图阻止表单提交。例如,用户不能将所有输入都设为0,但至少在其中之一上放1,这样所有投入的总价值至少为1。

I have created a method in jquery validate to check if the value is greater than 0 of the selected inputs 我在jquery validate中创建了一个方法来检查值是否大于所选输入的0

<td><input class='{nbTeams: true} nbTeamsVal' type="text" class="form-control" id="nbTeamsMiniSoccer_20" name="nbTeams[]"></td>
<td><input class='{nbTeams: true} nbTeamsVal' type="text" class="form-control" id="nbTeamsYouthMale_20" name="nbTeams[]"></td>

This is the method: 这是方法:

$.validator.addMethod("nbTeams", function(value, elem, param) {
  return $(".nbTeamsVal").value > 0;
  },"Collective value must be more than 1!"
);

This is my rule and custom message 这是我的规则和自定义消息

$(document).ready(function () {

  $('#myForm').validate({
      rules: {
          "nbTeams[]":{
            required: true
          }
      },
      messages: {
        "nbTeams[]":"This group of fields can only contain numbers and one must contain a value of at least 1."
      },
      errorElement : 'div',
      errorLabelContainer: '.errorTxt',
      submitHandler: function (form) { 
        form.submit();
      }
  });

});

i edit your code try this : 我编辑您的代码试试这个:

 $.validator.addMethod("nbTeams", function(value, elem) { var sumOfVals = 0; $(".nbTeamsVal").each(function () { sumOfVals = sumOfVals + parseInt($(this).val()); }); return sumOfVals>0; },"Collective value must be more than 1!" ); $('#myForm').validate({ rules: { "nbTeams[]":"nbTeams" }, errorElement : 'div', errorLabelContainer: '.errorTxt', submitHandler: function (form) { alert('valid form submitted'); // for demo return false; // for demo } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script> <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script> <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script> <form id="myForm" method="post" action="#"> <td><input class='{nbTeams: true} nbTeamsVal' type="text" class="form-control" id="nbTeamsMiniSoccer_20" name="nbTeams[]" value="0"></td> <td><input class='{nbTeams: true} nbTeamsVal' type="text" class="form-control" id="nbTeamsYouthMale_20" name="nbTeams[]" value="0"></td> <div class="errorTxt"></div> <button type="submit">Submit</button> </form> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM