Johann-S/bs-stepper

How to use Events to validate with jQuery Validate

medeiroshudson opened this issue · 4 comments

How can i use events listener to prevent next step if some field is null or white?

Hi @medeiroshudson,

You'll find an working example in the live documentation: https://johann-s.github.io/bs-stepper/

See: Form validation and the source code: https://github.com/Johann-S/bs-stepper/blob/master/docs/js/main.js#L31-L47

my problem is that in one step, there will be many fields... And with that method, will be necessary create something like

if (
                    (stepperPan.getAttribute('id') === 'escopoAnomalia' && !LocalAnomalia.value.length || stepperPan.getAttribute('id') === 'escopoAnomalia' && !AreaAnomalia.value.length || stepperPan.getAttribute('id') === 'escopoAnomalia' && !DataOcorrencia.value.length || stepperPan.getAttribute('id') === 'escopoAnomalia' && !OrigemAnomalia.value.length) || 
                    (stepperPan.getAttribute('id') === 'test-form-2' && !inputPasswordForm.value.length)
                    ) {
                    event.preventDefault()
                    form.classList.add('was-validated')
                }

for each form field. There is a easiest way?

There are a lots of solutions and easiest solutions, it's just a generic example to show what's possible to do.

For example, you can use jQuery serialize see: https://api.jquery.com/serialize/ to get all the forms values and validate them.

I had sucess using the jQuery Validate plugin. To initialize bs-stepper + jQuery Validate plugins i used:

 var stepperWizard = new Stepper($('.bs-stepper')[0], {
                linear: true,
                animation: true
            });

            var validator = $(".bs-stepper-content form").validate({
                rules: {
                    LocalAnomalia: {
                        required: true
                    },
                    AreaAnomalia: {
                        required: true
                    },
                    DataOcorrencia: {
                        required: true
                    },
                    OrigemAnomalia: {
                        required: true
                    }
                }
            })

            // BOTAO AVANCAR
            $('.btnNext').click(function () {

                var isValid = $("form").valid();

                if (!isValid) {
                    validator.focusInvalid();
                    event.preventDefault()
                }
                else {
                    stepperWizard.next();
                }

            });

            //BOTAO VOLTAR
            $('.btnPrevious').click(function(){
                stepperWizard.previous();
            });

maybe can useful for starters, like me :)