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.

Bootstrap Toggle Adding Dynamic Elements
MySQL Check All Tables in Database
 

Comments

No comments made yet. Be the first to submit a comment
Already Registered? Login Here
Guest
November 24, 2020

Captcha Image

By accepting you will be accessing a service provided by a third-party external to https://www.johnnyshongo.com/