Validation of bootstrap-select using Jquery Validate plugin
Asked Answered
W

5

7

I am facing problem to validate select which is beautified using bootstrap-select.js plugin using jquery validate plugin. bootstrap-select.js is expecting class selectpicker and following one line of code:

$('.selectpicker').selectpicker();

for beautifying select of html.

However it is causing problem in validations using jquery validate plugin. The select in not at all validated unless and untill class selectpicker in not removed. Once class is removed then validations are properly performed. Following is my html for select:

<select class="input-medium required" id="editCategory_sltCategoryName"
name="editCategory_sltCategoryName">
    <option value="">
        Select Category
    </option>
    <option>
        Reusable Components
    </option>
    <option>
        BU Connects
    </option>
</select>

and following is the js:

$('#frm_editCategory').validate({
    rules: {
        editCategory_sltbuName: {
            required: true
        },
        editCategory_sltCategoryName: {
            required: true
        },
        editCategory_categoryName: {
            minlength: 2,
            required: true,
            buname: true
        },
        editCategory_categoryDescription: {
            minlength: 2,
            required: true,
            buname: true
        }
    },
    highlight: function(element) {
        $(element).closest('.control-group')
            .removeClass('success').addClass('error');
    },
    success: function(element) {
        element.text('OK!').addClass('valid')
            .closest('.control-group')
            .removeClass('error').addClass('success');
    },
    submitHandler: function(event) {
        return true;
    }
});

I have tried to do it by writing custom method for it also but it is of no use.

Whacking answered 19/8, 2013 at 13:38 Comment(0)
E
20

I'll do my best to answer your question based on what you've described, because I believe I have encountered a similar issue and been able to resolve it.

First, I'm assuming that you correctly initialized your select with the selectpicker() method. Above, you wrote

$('.selectpicker').selectpicker();

But you do not have any select elements with class selectpicker, so I think what you meant to write was

$('select').selectpicker();

When you call selectpicker(), Bootstrap will insert additional elements (div, button, span, ul, and li) after your select element. But note that, Bootstrap will then hide() your original select element. Because your select is hidden, JQuery Validate will ignore validation of it when the form is submitted. This is the main issue.

To tell Jquery Validate not to ignore your hidden select inputs, you can do the following...

// Initialize form validation rules, submit handler, etc.
$('#frm_editCategory').validate({
  .
  .
  .
});

// The default value for $('#frm_editCategory').validate().settings.ignore
// is ':hidden'.  Log this to the console to verify:
console.log($('#frm_editCategory').validate().settings.ignore);

// Set validator to NOT ignore hidden selects
$('#frm_editCategory').validate().settings.ignore = 
  ':not(select:hidden, input:visible, textarea:visible)';

Why do you also need to include input:visible and textarea:visible? Before, the setting was to ignore all hidden inputs. If you only ignored :not(select:hidden), you would ignore any input which is not a hidden select. This is too permissive, though, because a visible input[type=text] is not a hidden select. So, it also would get ignored. What we want is to ignore any element which:

- is *not* a hidden `select`
- *is* a hidden `input`
- *is* a hidden `textarea`

To fit this all into a :not selector, you want to ignore any element which:

- is *not* a hidden `select`
- is *not* a visible `input`
- is *not* a visible `textarea`

Therefore...

$('#frm_editCategory').validate().settings.ignore = 
  ':not(select:hidden, input:visible, textarea:visible)';
Enervate answered 9/11, 2013 at 6:28 Comment(3)
Saved me a lot of time, thanks! The only issue is that it won't highlight the bootstrap select element red, however the required message appears and the validation prevents the form submission so that's a great start.Mickel
For myself I had legitimate hidden selects that I didn't want to validate, so I expanded it a bit to only handle the selectpickers: $('#form').validate().settings.ignore = ':not(select.selectpicker, select:visible, input:visible, textarea:visible)';Mickel
Nice one here!... Crisp & clear & giving ideas on customization options... I've never really been the guy who loves fiddling with the client side of things, but this got me going really quickly. The OP should mark this as the confirmed answer. I wish I could upvote multiple times.Confuse
S
6
$('#frm_editCategory').validate({
    ignore: ":hidden:not(.selectpicker)"
});
Saber answered 22/9, 2013 at 22:26 Comment(0)
C
4

Here's what worked flawlessly for me:

jQuery / javascript:

$(document).ready(function() {
    $.validator.setDefaults({
        /*OBSERVATION: note how the ignore option is placed in here*/
        ignore: ':not(select:hidden, input:visible, textarea:visible)',

        /*...other options omitted to focus on the OP...*/

        errorPlacement: function (error, element) {
            if (element.hasClass('bs-select')) {
                error.insertAfter('.bootstrap-select');
            } else {
                error.insertAfter(element);
            }
            /*Add other (if...else...) conditions depending on your
            * validation styling requirements*/
        }
    });

    $('#myform').validate({ 
        rules: {
            'year': {
                required: true
            }
        },
        messages: {
            'year': {
                required: 'Please select a year from the dropdown'
            }
        }
    });
});

HTML:

<select class="input-medium bs-select required">
    <option value="">Select Category</option>
    <option>Innovation</option>
    <option>Reusable Components</option>
    <option>BU Connects</option>  
</select>

Explanation:

OBSERVATION: Based on @Alvin Lee's answer setting the ignore options on the form element as follows was ok, but had its caveats;

$('#myform').validate().settings.ignore = 
    ':not(select:hidden, input:visible, textarea:visible)';

The Problem: The bootstrap select element got validated but showed the default message This field is required on every other input element instead of overriding it with all the custom validation messages that were previously configured.

The fix: move the ignore setting into $.validator.setDefaults({...}) block... That should do it!

Confuse answered 6/2, 2015 at 12:11 Comment(0)
E
2

Here is simple solution which worked for me:

var validator = $('#frm_editCategory').validate({
    .
    .
    .
});

$('select.input-medium').on('change', function () {
    validator.element($(this));
});

That's it

Elroy answered 3/1, 2017 at 18:48 Comment(0)
S
0

In my case this tric work *.js

`$("#form_id").validate({
     rules: {
       field_name: { required: true },
     },
     submitHandler: function (form) {
            form.submit();
     }
    }).settings.ignore = 
    ':not(select:hidden, input:visible, textarea:visible)'
`

*.html

    <select data-style="btn-default" class="selectpicker" name="class_id" id="class_id">
      <option value="" selected disabled hidden>Placeholder</option>
      <option value="value1">Value 1</option>
    </select>
Sinus answered 30/8, 2022 at 6:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.