Form Validator - Multi-Steps Example

by bizamajig

HTML

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/additional-methods.js"></script>
<form id="form1">Step #1
    <input type="text" name="field1" /><br />
    <button type="button" id="gotoStep2">Go to step 2</button>
</form>
<form id="form2">Step #2
    <input type="text" name="field2" /><br />
    <button type="button" id="gotoStep3">Go to step 3</button>
</form>
<form id="form3">Step #3
    <input type="text" name="field3" /><br />
    <button type="submit">Complete</button>
</form>
<a href="http://docs.jquery.com/Plugins/Validation" target="_blank">Validation Documentation</a>

CSS

#form2, #form3 {
    display: none;
}

a {
    display: block;
    position: absolute;
    bottom: 0;
}

JavaScript

$(document).ready(function() {

    $('#form1').validate({
        // rules
        rules: {
            field1: {
                required: true
            }
        }
    });

    $('#form2').validate({
        // rules
        rules: {
            field2: {
                required: true
            }
        }
    });

    $('#form3').validate({
        // rules,
        rules: {
            field3: {
                required: true
            }
        },
        submitHandler: function (form) {
            // serialize and join data for all forms
            var data = $('#form1').serialize() + '&' + $('#form2').serialize() + '&' + $(form).serialize();
            // ajax submit
            alert(data);
            return false;
        }
    });

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

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

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

});