Search code examples
jqueryjquery-uijquery-validatejquery-ui-multiselect

Multi Select Custom Validation Rule


I'm trying to create a custom validation rule to ensure that at least one selection is made within a select with the multiple attribute. I have a jsfiddle showing what I have at this point but I can't get the validation rule to fire. I have included the jQuery script that is translating the select just in case this might be casing my issue. My code is in the document ready section at the bottom of the JavaScript window. The jsfiddle is here: https://jsfiddle.net/7bkz58cy/25/

$.validator.addMethod('multiSelectRequired', function (value, element) {
    return element.length > 0;
}, 'One selection required.');

$('#activity-dialog-form').validate({
    rules: {
        FacilityList: { multiSelectRequired: true }
    }
});

I can't figure out why the validation isn't firing. Can someone please point out what I'm missing.


Solution

  • I can't figure out why the validation isn't firing.

    One of the reasons your validation is not working is because you are calling the .validate() method twice on the same form. You can only call the .validate() method once, as all subsequent calls are completely ignored. Since your rules are declared in the second instance, they are ignored.

    The .validate() method would only ever be called once, on DOM ready, to initialize the plugin on your form, and this same instance contains any rules, options, callbacks, etc.


    In this most basic example, I simply put the required rule (required="required") on a select element, with a multiple="multiple" attribute, and the validation is working without custom rules/methods: https://jsfiddle.net/csj35fj8/

    Shown within your code: http://jsfiddle.net/Lzmh0qtg/2/

    $('#activity-dialog-form').validate({
        ignore: [],
        rules: {
            FacilityList: {
                required: true
            }
        },
        messages: {
            FacilityList: {
                required: 'One selection required.'
            }
        }
    });
    

    Since you're using the .multiselect() jQuery UI widget to dynamically change the appearance of the select field, you can no longer validate it as the original select element is now hidden.

    You will need to set the ignore option to [] in order to ignore "nothing" so that the hidden select is validated.


    In order to automatically hide the validation error message when the user makes a selection, use a change handler to trigger the .valid() method on this element.

    $('.multiselect').on('change', function() {
        $(this).valid(); 
    });
    

    This workaround is needed since the jQuery Validate plugin, by default, is only looking at events on the original select element, which is now hidden.

    Working DEMO: http://jsfiddle.net/Lzmh0qtg/3/