Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery.validate validation for non active tabs

I've a form which uses jQuery UI based tab to organize different fields. I'm using jquery.validate.min.js for validation. For example some fields have class = "required" which informs the plugin for required field validation. Finally, before form submit I validate the form to ensure all inputs are correct. A simple usage like -

HTML

...
<input type="text" class = "required" ...

SCRIPT

...
$("#frmClaim").validate();//to initilize validation
...
$('#frmClaim').submit(function () {            
             if($(this).valid())
                { ... }
         });
...

The issue I'm facing is that if I'm on tab 3 and there's a "required" field on tab 2 which the user has not populated, the validation is NOT performed. The validation triggers only for the fields which are visible - that is the active. Is this possible or am I missing something?

For now, on submit I manually activate each tab, perform .valid and proceed. Is there a better work around?

like image 998
Hemant Tank Avatar asked Jun 10 '13 07:06

Hemant Tank


2 Answers

Initialize validation like this to validate your hidden fields

$("#frmClaim").validate( 
 { ignore: [] }
);
like image 120
Dr Blowhard Avatar answered Nov 18 '22 18:11

Dr Blowhard


I found a solution that worked for me. The idea is to iterate for all tabs, calling validate on the form and stop when you find an invalid tab or submit the form if there is no invalid fields.

$("#my_form").validate({
        submitHandler: function (form, evt) {
            var f = $(form);
            var tab = $("#my_tab_id");
            var tabs_count = tab.children('ul').children('li').length;
            var active = tab.tabs('option', 'active');
            var invalid = false;
            var validated = 0;

            while (validated < tabs_count && !invalid) {
                if (!f.valid()) {
                    invalid = true;
                    break;
                }

                active++;
                active = active % tabs_count;
                tab.tabs('option', 'active', active);

                validated++;
            }

            if (!invalid)
                form.submit();
            else
                evt.preventDefault();
        },
        rules: {
            ...
        },
        messages: {
            ...
        }
    });
like image 35
José Andrés Avatar answered Nov 18 '22 18:11

José Andrés