jQuery validate dynamic input array

37,663

Quote OP: "And so strangely this plugin does not work:
$(this).validate({ ... });"

It's not strange. It's not working because you have not really targeted anything. There's no context or scope for $(this) to have any meaning.

You must properly target your <form> element:

for example, by id...

$('#myform').validate({ ... });

...or by any other valid jQuery selector that targets the actual <form></form> you want validated.


Here is a generic example of how to validate a select element that you can easily adapt into your situation:

http://jsfiddle.net/Gy24q/

Important, the very first, or the default option in the select element must contain value="" or the required rule will fail. If, for whatever reason, you cannot set this first option's value equal to "", then see this answer's custom method workaround and jsFiddle.

HTML:

<form id="myform">
    <select name="id_material[]">
        <option value="">please choose...</option>
        <option>option 1</option>
        <option>option 2</option>
        <option>option 3</option>
    </select>
    ....
</form>

Since your name contains brackets, [], you also must enclose your field name in quotes:

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize plugin within DOM ready
        // other options,
        rules: {
            'id_material[]': {
                required: true
            }
        },
    });

});

The above answer assumes you know the name of the select element. However, if you don't know the name, you have a couple options...

1) Use class="required" inside the select element...

<select class="escolhaVidro id_material required" name="id_material[]" id="id_material">

Demo: http://jsfiddle.net/Gy24q/4/

2) If the rules are more complex, you can add compound rules based on your existing class assignments using the rules('add') method.

Use jQuery .each() if you have more than one select element that needs this rule...

// must be called after validate()
$('select.id_material').each(function () {
    $(this).rules('add', {
        required: true
    });
});

Demo: http://jsfiddle.net/Gy24q/10/

Otherwise, this will only apply the rule to only one select element with class id_material...

$('select.id_material').rules('add', {
    required: true
});

EDIT:

Quote OP in comments:

Inside the function following validation is performed: $('#formOrcamento').live('submit', function() {...}); Then $(this).validate({...}); refers to: $('#formOrcamento').validate ({...});

same as:

$('#formOrcamento').live('submit', function() {
    $(this).validate({ ... });
});

Yes, this is exactly why it's broken.

.validate() only gets called once on DOM ready to initialize the plugin. You are not supposed to put it inside a submit handler. The Validate plugin already has its own built-in event handler that captures the form's submit button.

Setup your code as per my working jsFiddle demos above.


EDIT 2:

Quote OP in comments:

I'm using jquery-ui and this adds to the select the following: style='display: none'. If I remove via Firebug the display: none, then select validation occurs and displays the label error correctly. What might be happening?

The Validate plugin ignores hidden elements by default. You'll need to turn that option off by adding ignore: [] to validate():

$(document).ready(function () {

    $('#myform').validate({
        ignore: [], // to allow validation of hidden elements
        // other options,
    });

});

See this answer for more information.

Share:
37,663
Maykonn
Author by

Maykonn

Solid knowledge on: I'm a web backend software architect 10+ years working with programing problems, especially on distributed cloud solutions Backend, APIs, microservices and cloud infrastructure specialist Architecture and development of RESTful APIs Complex and critical problem solving GoF Patterns, DDD, SOLID Programming concise, clean, without coupling, easy maintainability, safe and performance. Laravel, Symfony, Zend, Yii, and much more Redis and Memcached as cache or DB Apache, Nginx, Node.js Relational and NoSQL databases UML, analisys, management, engineering and software architecture Agile Development and Classics Methodologies Versioning, GIT, SVN https://github.com/maykonn

Updated on October 23, 2021

Comments

  • Maykonn
    Maykonn about 2 years

    How to validate a <select> when this is a dynamic array? Like this:

    <select class="escolhaVidro id_material" name="id_material[]" id="id_material">
    

    To clarify: This <select> assembled dynamically by PHP, so I do not know what are the indexes, so this way is not possible:

    $(this).validate({
        rules: {
            "id_material[index]" : {
                required : true
            }
        }
    });
    

    And so strangely this plugin does not work:

    $(this).validate({
        rules: {
            id_material : {
                required : true
            }
        }
    });
    

    I also tried to use a CSS class required in <select>, but no good.

  • Maykonn
    Maykonn over 10 years
    Inside the function following validation is performed: $('#formOrcamento').live('submit', function() {...}); Then $(this).validate({...}); refers to: $('#formOrcamento').validate ({...});
  • Sparky
    Sparky over 10 years
    @MayW. Take .validate() out of your live.submit handler. It's not necessary and the most likely reason it's broken. Follow my working demos above and see my edits.
  • Maykonn
    Maykonn over 10 years
    I'm using jquery-ui and this adds to the select the following: style='display: none'. If I remove via Firebug the display: none, then select validation occurs and displays the label error correctly. What might be happening?
  • Sparky
    Sparky over 10 years
    The Validate plugin ignores hidden elements by default. You'll need to turn that option off by adding ignore: [] to validate(). See: jsfiddle.net/Gy24q/6
  • Maykonn
    Maykonn over 10 years
    I applied the fixes that indicated and are much better. However only one of the select is being validated. Then modified to, as you said after .validate(): $('select.id_material').rules('add', {required: true,}); But still only one of select is being validated.
  • Sparky
    Sparky over 10 years
    @MayW., yes, and that's exactly what I said was going to happen. Go back and re-read that section of my answer... you must use .each() if you have more than one select.id_material. See the demo: jsfiddle.net/Gy24q/10
  • Maykonn
    Maykonn over 10 years
    $('select.id_material').rules('add', {required: true,}); was not working because these select are added or removed as the user interacts and makes decisions, then through a setInterval() solved this. Another problem, which is simple but not me I saw so fast, is that the name from select were always as name=id_material[] then added a counter i++ thereby: name=id_material[i]and everything works perfectly now.
  • user9437856
    user9437856 over 3 years
    @Sparky, Is there any link where I can check the submitting process in php or codeigniter?