Validation in Multi Step Form

Alexander edited this page Jun 29, 2013 · 8 revisions

If you have a multi step form and want to enable client side validation on completion of each step, use the following code. Basically, on click of next button, perform validation on each of the visible form fields.

$("#NextButton").bind("click", function(e) {
  //If the form is valid then go to next else don't
  var valid = true;
  // this will cycle through all visible inputs and attempt to validate all of them.
  // if validations fail 'valid' is set to false
  $('[data-validate] input:visible').each(function() {
    var settings = window.ClientSideValidations.forms[this.form.id]
    if (!$(this).isValid(settings.validators)) {
      valid = false
    }
  });
  if(valid){
    //code to go to next step
  }
  // if any of the inputs are invalid we want to disrupt the click event
  return valid;
});

Then, when new form elements are visible, you need to enable the validators again (by default, Client Side Validations only validates visible fields):

$(form_id).enableClientSideValidations();

Old versions (< 3.2)

If you have an older version of Client Side Validations, replace

    var settings = window.ClientSideValidations.forms[this.form.id]

with

    var settings = window[this.form.id];

and ignore the code to add validators to previously hidden fields because it is not needed.