Validation of bootstrap-select using Jquery Validate plugin

一笑奈何 提交于 2019-12-18 05:00:17

问题


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.


回答1:


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)';



回答2:


$('#frm_editCategory').validate({
    ignore: ":hidden:not(.selectpicker)"
});



回答3:


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!




回答4:


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



来源:https://stackoverflow.com/questions/18315242/validation-of-bootstrap-select-using-jquery-validate-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!