简体   繁体   中英

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.

I have created a method in jquery validate to check if the value is greater than 0 of the selected inputs

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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