JQuery Validate Multiple Dynamic Inputs

JQuery Validate Multiple Dynamic Inputs

I'm using this great jQuery Validation Plugin to validate my form, and some dynamic inputs that users can add when clicking a button.


I add new dynamic inputs and they all share the same name, this is because I want to send these values as an array to PHP. For example;

//HTML

<input type="text" name="test[]">
<input type="text" name="test[]">
<input type="text" name="test[]">
<input type="text" name="test[]">

//PHP
$test = $_POST['test']; 

The issue with the validation plugin is that it only validates the first element of the 'name[]' inputs.


We can override this functionality, without changing any of the core files. Add this code to the page where your form is, above the $("#myform").validate() function.

$.validator.prototype.checkForm = function() {
    //overriden in a specific page
    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();
}; 

Hope this helps.

Rate this blog entry:
MySQL Check All Tables in Database
Bootstrap Toggle Adding Dynamic Elements

Comments

 
No comments yet

Latest Comments

Susan Hermiston Virtual Hosts
October 7, 2015
Wow 747 just blew me away. Sorry not a tech person at all!! But I still love you!! Rock on!!?
Johmny Invisible Mouse Cursor Ubuntu & Synergy
September 2, 2015
Glad I was ble to help!
Kristian Falk Invisible Mouse Cursor Ubuntu & Synergy
September 1, 2015
Thank you for this! Had the exact same problem. I almost went crazy.