How can I validate repeatered form?

2.4k views Asked by At

I want to use both jquery repeater and jquery validation library. Here my validate rules:

$("#myForm").validate({
rules: {
    title: {
        required: true
    },
    subject: {
        required: true
    }
},
messages: {
    title: {
        required: "Enter title!"
    },
    subject: {
        required: "Enter subject!"
    }
},
errorElement: 'div',
errorPlacement: function (error, element) {
    var placement = $(element).data('error');
    if (placement) {
        $(placement).append(error)
    } else {
        error.insertAfter(element);
    }
},
submitHandler: function (form) {
    submitForm();
    return false;
}
});

but it is not working. Because jquery repeater creates input name like data[0][title], data[1][title], data[0][subject], data[1][subject], etc. Therefore my rules are not working just naming title or subject. How can I validate these name like data[*][title] and data[*][subject] ?

1

There are 1 answers

0
Sparky On

As stated in my comment, you cannot set rules from within the .validate() method when the name is unknown. (If the name is missing, you cannot use this plugin.)

Keep in mind that unique names are mandatory for this plugin to function. Any of the techniques below still need a unique name on each field.

If simple rules like required need to be set, then you can declare them inline with data attributes, HTML5, or classes. required="required", class="required", etc. and the plugin will pick them up automatically.

<input name="foo" required="required" ....

If you cannot alter the inline HTML, then you can use the .rules() method to add rules to these fields as long as they exist at the time you've called .rules('add').

  1. Call .validate() on your form to initialize the plugin with your options.

  2. Create your new fields using Repeater or whatever method, making sure that all new fields have a unique name attribute.

  3. Call .rules('add') insides of a jQuery .each() that is attached to a jQuery selector such as "ends with" on these new fields. This will dynamically add the required rule to all fields with a name that ends with the string [subject]...

    $("[name$='[subject]']").each(function() {
        $(this).rules('add', 
            required: true,
            messages: {
                required: "optional custom message"
    
        });
    });