1

I am using jQuery Validate plugin ( jqueryvalidation.org ) and trying to validate dropdown. The problem is that my dropdown use bootstrap-select plugin and that means library converts "normal" dropdown into div (for styling, live-search etc.) more info about boostrap-select - https://silviomoreto.github.io/bootstrap-select/examples/.

My question is how can I use jQuery Validator plugin options on this boostrap-select dropdown.

Here is my code

echo $this->Form->input('customer_number', [
 'options' => $customer_number_list,
 'id' => 'customer_number',
 'class' => 'selectpicker',
 'empty' => __('All'),
 'label' => __('Customer number'),
 'value' => $this->request->data['customer_number'] ?? '',
 'onchange' => 'getDestinationList()'
]);

And below is jQuery Validator configuration (rules and messages)

<script type="text/javascript" src="/js/jquery-validation/jquery.validate.js"></script>
<script>
  $(document).ready(function() {
    $('#change_destination').validate({
      rules: {
        customer_number: {
          required: true
        }
      },
      messages: {
        customer_number: {
          required: 'Please select a template'
        }
      },
      submitHandler: function(form) { // blocks submission for demo
        $('.selectpicker').selectpicker('refresh');
        return false;
      }
    });
  });
</script>

This code works if I change my dropdown class in form-control (but then my dropdown doesnt have "nice" look and other features what I am getting from bootstrap selectpicker library. Here is an example of Bootstrap dropdown library (https://silviomoreto.github.io/bootstrap-select/examples/)

Thank you

Sparky
  • 98,165
  • 25
  • 199
  • 285
JohnWayne
  • 651
  • 9
  • 28
  • Your actual dropdown probably exists somewhere in the DOM, but is likely hidden with CSS. Find that hidden element, figure out the selector (devtools will help with that) and try validating against it. – bcosynot Jun 02 '17 at 08:44
  • You have right, real select element exists in body and it is hidden, but jQuery Validator plugin doesnt generate "error" message because if you select something from dropdown - selected tag doesnt appear in real select element, it shows up only in that div list from bootstrap-select... – JohnWayne Jun 02 '17 at 08:47

1 Answers1

4

Problem is that select option is hidden and in jQuery validator configuration is written - ignore hidden elements so you have to change jQuery Validation library configuration file:

ignore: ":hidden"

into

ignore: ""

You can find this options from line 255 - 265 based on jQuery library version. More info about the same problem you can find on GitHub bootstrap-select issues -> https://github.com/silviomoreto/bootstrap-select/issues/215

I hope so that this works for you!