13

I have the following form. I am trying to validate the inputs using jquery validation plugin. I have tried some codes but its not working. When I click on the submit button it just goes to form's action.

<form name="voucherform" action="something" method="post">
  <input type="text" name="reg_number[]" value="" />
  <input type="text" name="reg_number[]" value="" />
  <input type="text" name="reg_number[]" value="" />
  <input type="submit" name="submit" value="submit" />

Could you please show me how to validate the above form using jquery validation plugin?

Thanks :)

My Jquery code:

 <script type="text/javascript" src="<?php echo base_url();?>support/datepicker/js/jquery-1.7.2.min.js"></script>
 <script type="text/javascript" src="<?php echo base_url();?>support/js/jquery.validate.js"></script>

 <script>
  $(document).ready(function() {

// validate signup form on keyup and submit
var validator = $("#voucherform").validate({
    showErrors: function(errorMap, errorList) {
        $(".errormsg").html($.map(errorList, function (el) {
            return el.message;
        }).join(", "));
    },
    wrapper: "span",
    rules: {

        reg_number[]: {
            required: true,
            minlength: 2,
            remote: {
                url: '<?php echo base_url();?>sales/invoice_check', async: false,
                type: 'post'
            },

        }
    },
    messages: {

        reg_number[]: {
            required: "Enter Reg Number",
            minlength: jQuery.format("Enter at least {0} characters"),
            remote: jQuery.format("{0} is already in use")
        },
    }
    });
    });
   </script>
black_belt
  • 6,601
  • 36
  • 121
  • 185
  • I found the best answer here https://stackoverflow.com/a/17643385/146553 if your element names have indexes they are treated as unique names req_number[0] req_number[1] ect.... – todd Sep 23 '13 at 13:33

4 Answers4

16

You have two problems:

  1. You aren't selecting the form element properly.

    You're looking for a form with id "voucherform" and your markup does not contain one. You probably want to change your selector to:

    $("form[name='voucherform']").validate({ ... });
    
  2. Brackets ([]) are not valid in JavaScript identifiers. This means that your script is not being parsed correctly. To resolve this, just wrap those fields that have brackets in them in quotes, i.e. 'reg_number[]' instead of reg_number[].

Tweaked validate code:

var validator = $("form[name='voucherform']").validate({
    showErrors: function(errorMap, errorList) {
        $(".errormsg").html($.map(errorList, function(el) {
            return el.message;
        }).join(", "));
    },
    wrapper: "span",
    rules: {
        'reg_number[]': {
            required: true,
            minlength: 2,
            remote: {
                url: '<?php echo base_url();?>sales/invoice_check',
                async: false,
                type: 'post'
            }

        }
    },
    messages: {
        'reg_number[]': {
            required: "Enter Reg Number",
            minlength: jQuery.format("Enter at least {0} characters"),
            remote: jQuery.format("{0} is already in use")
        }
    }
});

Example: http://jsfiddle.net/hfrhs/

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • 4
    I am sorry but I thought you solution was working perfectly but I just noticed now that if you put a value in the first input and then click on submit the system doesn't show the the error messages for leaving rest of the inputs blank :( – black_belt Jun 01 '12 at 11:05
  • @black_belt: Is your remote rule working correctly? If it fails it might cause the rest of the validation to fail. – Andrew Whitaker Jun 01 '12 at 12:11
  • 1
    He is right, this solution does not work.. if you never focus the other inputs the validation only works for the first line of elements. – mlwacosmos May 24 '13 at 14:32
  • @mlwacosmos: Do you see the problem in the example? – Andrew Whitaker May 24 '13 at 15:29
  • 2
    It looks like the plugin cannot work in this case... there is another stackoverflow post... something has to be changed in jquery.validate.js : http://stackoverflow.com/a/4136430/432513 ans especially this url : http://www.codeboss.in/web-funda/2009/05/27/jquery-validation-for-array-of-input-elements/ – mlwacosmos May 24 '13 at 15:35
  • Doens't work like this. See answer from @todd. Add array keys – Richard Dec 06 '16 at 09:03
5

You can find a good answer here: jquery-validation-for-array-of-input-elements. In jquery.validate.js, we can find a function named checkForm, we have to modify it as below:

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();
}
Alex
  • 1,033
  • 4
  • 23
  • 43
2

here is my way

 'reg_number[]':{ 
    required:function(){
      return $("input[name='reg_number[]']").filter(function(){
        return $.trim($(this).val()).length>0
      }).length==0
    }
 }

Hope it has little help for you.

RanchoX
  • 5
  • 4
user995789
  • 279
  • 1
  • 4
  • 15
0

Just sharing a method to validate checkbox with index and only one of them is mandatory.

<input type="checkbox" value="0" name="is_appraisal[0]" class="is_appraisal_f siblingcheckbox" id="is_appraisal_f">

<input type="checkbox" value="1" name="is_appraisal[1]" checked="checked" class="is_appraisal_s siblingcheckbox" id="is_appraisal_s">

Jquery Validation for this :

       $.validator.addMethod("onechecked", function (value, elem, param) {
            if ($(".siblingcheckbox:checkbox:checked").length > 0) {
                return true;
            } else {
                return false;
            }
        }, "You must select at least one!");

        $.validator.addClassRules("siblingcheckbox", {
            onechecked: true
        });
Bugfixer
  • 2,547
  • 2
  • 26
  • 42