I have developed a small wizard script natively, something different and different from the normal wizards.
A bit of how it works
My wizard avoids losing the data entered in the form and preserves the step in which the user is, even if the page is reloaded or the user clicks on another link by mistake or when closing the tab, the data and the steps are preserved, with this prevents the user from having to repeat the steps again from scratch (except if the user closes the browser) .
The problem is that if the user leaves empty form fields, the user can continue/advance to the next step and this should not happen. I need to validate the form fields at each step to prevent it from continuing to the next step if the form fields are not filled in correctly.
The idea is to create validations such as the following wizard or this other wizard , if you click on continue to the next step, leaving the input
form fields empty, this throws an error below or on the sides for each of the input
empty fields, thus avoiding continuing to the next one step.
In the examples you can see that its validation is validating according to its container within the current step, before continuing to the next step.
The HTML structure of my wizard could be said to be the same, each step has its container with its unique IDstep1, step2, step3 etc...
<?php include 'php/wizard.php' ?>
<!-- dato importante para el funcionamiento wizard -->
<script type="text/javascript">
var step = <?php echo $step ?>;
var radio = <?php echo $radio ?>;
</script>
<form id="form">
<div id="step1" class="step">
<h1>Paso 1</h1>
<!-- Diferentes tipos de campo input u otros que se necesitan validar-->
<a href="#" onclick="show_step('2')">continuar</a>
</div>
<div id="step2" class="step">
<h1>Paso 2</h1>
<!-- Diferentes tipos de campo input u otros que se necesitan validar-->
<a href="#" onclick="show_step('1')">Atras</a>
<a href="#" onclick="show_step('3')">continuar</a>
</div>
<div id="step3" class="step">
<h1>Paso 3</h1>
<!-- Diferentes tipos de campo input u otros que se necesitan validar-->
<a href="#" onclick="show_step('2')">Atras</a>
<a href="#" onclick="show_step('4')">continuar</a>
</div>
<div id="step4" class="step">
<h1>Paso 4</h1>
<!-- Diferentes tipos de campo input u otros que se necesitan validar-->
<a href="#" onclick="show_step('3')">Atras</a>
<input><-- Finalizar
</div>
</form>
My Wizard
Note: The form validations must be validated natively using only jQuery/PHP without using libraries or plugins.
function show_step(step){
var data = $( "#form" ).serialize();
var url = 'saveTemp.php?step=' + step;
// recuperamos el lavel del radio button seleccionado
//var valor_radio = $('input:radio[name=radio]:checked').next("label").text();
$.ajax({
type: "POST",
url: url,
data: data
}).done(function(resp){
step = parseInt(step);
$('#address').val(resp.address);
$('#email').val(resp.email);
$('#name').val(resp.name);
$('#phone').val(resp.phone);
$('#radio').val(resp.radio);
$('#username').val(resp.username);
if (step === 2) {
var radio = parseInt(resp.radio);
switch(radio) {
case 1:
urlform = './app/themes/pay_paypal.php'
break;
case 2:
urlform = './app/themes/pay_paypal2.php'
break;
case 3:
urlform = './app/themes/pay_paypal3.php'
break;
default:
urlform = './app/themes/pay_paypal4.php'
break;
}
$('#divPago').load(urlform,function(responseTxt, statusTxt, xhr){
if(statusTxt === "success") {
$('.step').css( "display", "none" );
$('#step'+ step).fadeIn("slow");
animacion(step);
}
if(statusTxt === "error") {
//
}
});
} else {
$('.step').css( "display", "none" );
$('#step'+ step).fadeIn("slow");
animacion(step);
}
});
};
$(function() {
show_step(step);
});
Based on this problem:
Una solución a tu problema es buscar y validar solo aquellos campos dentro del paso actual, antes de continuar al siguiente.
Si solo te interesa validar:
radio
ocheckbox
, al menos uno este seleccionadoinput
(distinto deradio
ochecbox
),select
otextarea
, no estén vacíosEntonces podrías hacer algo simple como esto:
Ejemplo:
It depends a lot on the validation you want to do, for example if you want to validate that none of the inputs is empty just using Jquery you can do the following:
you can customize the selector "$()" according to the inputs you want to check, example:
In the case of checkboxes, the "if()" must be done in the following way:
To stop the function completely before the loop you can place a variable to check, it would look something like this:
Mi alternativa de solución es la siguiente. la validación se aplica por tipos ,
input textarea , select
, (esto puede variar) solo se valida que no esté vacíos y que esté un elemento seleccionado de unselect
. Para la validación utilizo unarray
para ir añadiendo los errores y los elementos donde se producieron.Aparte de la validación con JQuery , se podría ir mostrando los mensajes por ejemplo cuando el input no es válido , esto se podría lograr añadiendo el atributo
pattern
alinput
con la validación que se requiera por ejemplopattern="[0-9]{6,11}"
para que ingrese mínimo 6 y máximo 11. , El código está comentadoThis is an example of how to make a form in steps and that validates the fields step by step, in which validations have been included for the following types of fields:
text
with minimum and maximum characters optionally, the range can be set withdata-min
anddata-max
.tel
to validate phones, based on a regex (/^(?:(?:\+|00)?34)?[6-9]\d{8}$/
).textarea
with minimum and maximum characters optionally, the range can be set withdata-min
anddata-max
.select
andselect multiple
, requiring at least one option to be selected.radio
requiring that at least one option be selected.checkbox
requiring this to be selected.Fields that require validation must have the attribute
required
.You can customize the error messages for each field by including one
span
with the classwizard-message
inside thelabel
.Sending is prevented by default with the key
ENTER
if we are not in the last step.Classes
.next
and are used.back
to move forward or backward.The last step must be set, for this we can use the attribute
data-end
on the tagform
or set the property directly withendStep
To define a form step we use a div tag with the class
wizard
and an idwizard-N
where N represents the step number.The bookcase has been used
Bootstrap
to give a little style. The rest is js and JQuery.I have commented the code to make it easy to understand.
As I indicated in the comments, it is easy to adapt the script to your code. I leave here an example with your code.