8

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.

Sparky
  • 98,165
  • 25
  • 199
  • 285
Maykonn
  • 2,738
  • 6
  • 33
  • 51

2 Answers2

11

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.

Community
  • 1
  • 1
Sparky
  • 98,165
  • 25
  • 199
  • 285
  • Inside the function following validation is performed: `$('#formOrcamento').live('submit', function() {...});` Then `$(this).validate({...});` refers to: `$('#formOrcamento').validate ({...});` – Maykonn Feb 18 '13 at 20:17
  • 1
    @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. – Sparky Feb 18 '13 at 20:40
  • 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? – Maykonn Feb 18 '13 at 20:47
  • 1
    The Validate plugin ignores hidden elements by default. You'll need to turn that option off by adding `ignore: []` to `validate()`. See: http://jsfiddle.net/Gy24q/6/ – Sparky Feb 18 '13 at 20:51
  • 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. – Maykonn Feb 18 '13 at 21:17
  • @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: http://jsfiddle.net/Gy24q/10/ – Sparky Feb 18 '13 at 21:30
  • `$('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. – Maykonn Feb 19 '13 at 18:20
  • @Sparky, Is there any link where I can check the submitting process in php or codeigniter? – user9437856 Apr 07 '20 at 20:14
-2

Just use emtpy brackets and make sure the name including brackets is in quotation marks (see documentation):

$(this).validate({
    rules: {
        "id_material[]" : {
            required : true
        }
    }
});
Adam
  • 25,960
  • 22
  • 158
  • 247