In this example, you will learn how to use FormValidation to validate a multiple steps wizard. The wizard is actually a normal form but is split into multiple steps. By default, all steps are hidden except the active one.
We can imagine that the form is structured as following:
<style>
.js-step {
// By default, all steps is hidden
display: none;
}
.js-step-active {
// Show the current step
display: block;
}
</style>
<form id="demoForm" method="POST">
<div class="js-step js-step-active" data-step="1">...</div>
<div class="js-step" data-step="2">...</div>
<button type="button" id="prevButton">Prev</button>
<button type="button" id="nextButton">Next</button>
</form>
We initialize a FormValidation instance for each step. Also, we will bring user to the next step when a step is successfully validated:
const demoForm = document.getElementById('demoForm');
const step1 = demoForm.querySelector('.js-step[data-step="1"]');
const step2 = demoForm.querySelector('.js-step[data-step="2"]');
const prevButton = demoForm.querySelector('[id="prevButton"]');
const nextButton = demoForm.querySelector('[id="nextButton"]');
let currentStep = 1;
const fv1 = FormValidation
.formValidation(
step1,
{
fields: {
...
},
plugins: {
...
},
}
)
.on('core.form.valid', function() {
currentStep++;
nextButton.innerHTML = 'Purchase';
FormValidation.utils.classSet(step1, {
'js-step-active': false,
});
FormValidation.utils.classSet(step2, {
'js-step-active': true,
});
});
const fv2 = FormValidation
.formValidation(
step2,
{
fields: {
...
},
plugins: {
...
},
}
)
.on('core.form.valid', function() {
nextButton.innerHTML = 'Done';
});
The sample code uses the built in method, FormValidation.utils.classSet, to set the CSS classes for given element.
Now, we need to validate the current step when clicking the
Next button. It can be done via the
validate() method:
nextButton.addEventListener('click', function () {
switch (currentStep) {
case 1:
fv1.validate();
break;
case 2:
fv2.validate();
break;
default:
break;
}
});
Going to the previous step is much simple:
prevButton.addEventListener('click', function () {
switch (currentStep) {
case 2:
currentStep--;
nextButton.innerHTML = 'Next';
FormValidation.utils.classSet(step2, {
'js-step-active': false,
});
FormValidation.utils.classSet(step1, {
'js-step-active': true,
});
break;
case 1:
default:
break;
}
});
This example only has two steps, but we can use the same approach if your wizard has more steps. You can play with it in the demo below:
See also