imjp
imjp

Reputation: 6695

jQuery: Validating fields before submitting (multistep form)

I have a form which consists of 2 steps. What I'd like to do is validate each step before continuing to the next; the user should not be able to get to step 2 of step 1's fields are invalid.

js fiddle: http://jsfiddle.net/Egyhc/
Below you can find the simplified version of the form:

<form>
  <div id="step1" style="display: block;">
    <label for="first_name">First Name</label>
    <input type="text" value="" name="first_name" id="FirstName"/>

    <label for="last_name">Last Name</label>
    <input type="text" value="" name="last_name" id="LastName"/>
  </div>


  <div id="step2" style="display: none;">
    <label for="first_name">Address</label>
    <input type="text" value="" name="address" id="Address"/> 
  </div>

  <a href="#" id="step1_btn">Continue to step 2</a>
  <input type="submit" id="submit_btn" value="Verstuur" style="display: none;" />
</form>

$(function() {
  $('#step1_btn').click(function() {
    $('#step1').hide();
    $('#step2, #submit_btn').show();        
  });
});​

How do you guys suggest I achieve this?

Upvotes: 4

Views: 9470

Answers (1)

Milimetric
Milimetric

Reputation: 13549

There's a very neat setting of jQuery validate that lets you ignore validation on hidden fields. So you can handle the show/hide logic of your steps and for validation you could just do this:

As this suggests: ignore hidden

$("form").validate({
   ignore: ":hidden"
});

If you need to check for validation on something besides the default form submit, you can use the valid method like this: $("form").valid().

I noticed you don't have any validation classes on your form, so I'm assuming you're handling that somewhere else. Just in case you're not, you can tell jQuery validate your rules through css classes like this: <input type="text" class="required digits"/>

See more here: http://bassistance.de/2008/01/30/jquery-validation-plugin-overview/

Upvotes: 6

Related Questions