Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating sections of a form

I've broken my form up into divs and using Next buttons to shop and hide those sections. I am also using jQuery Validation Plugin to do all the validation for me.

What I need to know is how to validate section by section. So this is what I have

  1. Personal Information
  2. Address details
  3. Project Information
  4. Terms and conditions

2,3,and 4 are hidden by default to make the form less daunting.

Clicking on the next button of Personal Information will hide this div and show the Address Details and so on.

The very last screen has the submit form button which then would validate the entire form normally but I need to validate each section before the user moves on.

Here's what I thought should have worked:

CSS

   .project-address {display:none;}

HTML

   <form class="wpcf7">
      <div class="project-details">
        <h2>Project details</h2>
        <label>Project name: </label><input type="text" class="reg-project-name" size="40" value="" name="projectName">
      <div class="back-next"><span class="reg-next-button">Next</span></div>
      </div>
      <div class="project-address">
        <h2>Project address</h2>
        <label>Project address:</label><input type="text" class="reg-project-address" size="40" value="" name="projectAddress">
      <div class="back-next"><span class="reg-next-button">Next</span></div>
      </div>
    </form>

JQUERY

    //clicking the next button hides this section and shows the next section
    jQuery('.project-details .reg-next-button').click(function() {

        // jQuery(".project-details").slideUp();
        // jQuery('.project-address').slideDown();          

        jQuery('.reg-project-name').validate({
            debug: true,
            rules: {
                projectName: "required"
            },
            messages: {
                projectName: "Please give your project a name",
            }
            });

             });

EDIT: Have tried to validate one element like this.

       jQuery('.project-details .reg-next-button').click(function() {

        // jQuery(".project-details").slideUp();
        // jQuery('.project-funding').slideDown();          
        var validator = jQuery( ".wpcf7-form" ).validate();
        validator.element( ".reg-project-name" );

    });

EDIT: If I click on the Next button, I need the form elements to be validated in that div before moving on which is not happening. i.e the form elements are not being validated..

Any thoughts? Many thanks.

like image 854
SixfootJames Avatar asked Aug 23 '13 11:08

SixfootJames


2 Answers

You can use the valid method on a selection of elements that you wish to validate.

Working Example:

// First, set up validator
$('#projectForm').validate({
  debug: true,
  rules: {
    projectName: "required"
  },
  messages: {
    projectName: "Please give your project a name",
  }
});

//clicking the next button hides the current section and shows the next section
$('.project-details .reg-next-button').click(function() {
    // Get the form that this button lives in
    var form = $(this).closest("form");
    // Get the validator object for the form
    var validator = form.data("validator");
    // Get the section that we're currently validating.  May need to modify this depending on the structure of your DOM
    var section = $(this).closest("div");
    // Get all controls (input, textarea, select, etc) in the section
    var fields = section.find(":input");
    if (fields.valid()){
      console.log("Valid!");
      // Hide this section...
      section.toggle();
      // And show the next section
      section.next().toggle();
    }
});
.project-address {
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>

<form id="projectForm">
  <div class="project-details">
    <h2>Project details</h2>
    <label>Project name: </label>
    <input type="text" class="reg-project-name" size="40" value="" name="projectName">
    <br>
    <button type="button" class="reg-next-button">Next</button>
  </div>
  <div class="project-address">
    <h2>Project address</h2>
    <label>Project address:</label><input type="text" class="reg-project-address" size="40" value="" name="projectAddress">
    <br>
    <button class="reg-next-button">Next</button>
  </div>
</form>

See this Codepen: http://codepen.io/alexweissman/pen/Wragog

like image 145
alexw Avatar answered Oct 15 '22 03:10

alexw


Firstly, forget about wrapping .validate() inside of any click handlers... it just doesn't work like that. One issue is that .validate() is not a method for "testing" the form's validity. Rather, .validate() is only the method for initializing the plugin on the form. You would do it once on page load, because any subsequent calls to .validate() are ignored.

To test the form programatically with the jQuery Validate plugin, you use the .valid() method which triggers a test and returns a boolean.

When I create multi-step forms, I use a unique set of <form> tags for each section.

Then I use .valid() to test the section before moving to the next. (Don't forget to first initialize the plugin; call .validate(), on all forms on DOM ready.)

Then on the last section, I use .serialize() on each form and concatenate them into a data query string to be submitted.

Something like this...

$(document).ready(function() {

    $('#form1').validate({
        // rules
    });

    $('#form2').validate({
        // rules
    });

    $('#form3').validate({
        // rules,
        submitHandler: function (form) {
           // serialize and join data for all forms
           // ajax submit
           return false;
        }
    });

    $('#gotoStep2').on('click', function() {
        if ($('#form1').valid()) {
            // code to reveal step 2
        }
    });

    $('#gotoStep3').on('click', function() {
        if ($('#form2').valid()) {
            // code to reveal step 3
        }
    });

    // there is no third click handler since the plugin takes care of this with the
    // built-in submitHandler callback function on the last form.

});

Important to remember that my click handlers above are not using type="submit" buttons. These are regular buttons, either outside of the form tags or type="button".

Only the button on the very last form is a regular type="submit" button. That is because I am leveraging the plugin's built-in submitHandler callback function on only the very last form.

"Proof of Concept" DEMO: http://jsfiddle.net/N9UpD/

Also, see for reference:

https://stackoverflow.com/a/17975061/594235

like image 40
Sparky Avatar answered Oct 15 '22 03:10

Sparky