Thursday , 23 March 2017
Home » jQuery » [jQuery] Validation of Input array Elements using jQuery
[jQuery] Validation of Input array Elements using jQuery

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

      
Plugin by: PHP Freelancer

About Rakshit Patel

I am PHP Freelancer, Rakshit Patel working as PHP Programmer India. I have developed this site to share my knowledge, thoughts and experience during the development of projects. We are group of developers working together. If you want to hire us for any PHP related work, you can reach me via Email, Phone or Chat.

3 comments

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

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Notify me of followup comments via e-mail. You can also subscribe without commenting.