8 February 2011 2 Comments

[jQuery] Validation of Input array Elements using jQuery

jQuery is one of the popular javascript library and becoming more and more popular as days passes. One of the javascript library of jQuery is validation for HTML forms. I always prefer to use jQuery validation. In one of my project, i was facing an issue with validating array of input elements using jQuery. After a long research, i found a solution and need to change a code in jquery.validate.js. Have a look at below code.

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

With using above code, it validates only for first name field. I need to validate all name fields. To achieve this, i made a changes in checkForm function of jquery.validate.js file. Follow the below steps.

1) Open jquery.validate.js file
2) Find checkForm: function() {
3) Replace this function with below code.

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();
}

You are done.

      
  • Trick

    Hi, this works perfect for me in Firefox, but not in IE7. Has anyone had the same problem and/or know any solution?
    Thanks!

  • Trick

    I’ve figured this has to do with me adding inputs dynamically.