Art Taylor
Art Taylor

Reputation: 492

jQuery Validation plugin validating form on button click

So I have a seven part form where six tabs are hidden via CSS and when a user clicks next another part fades in.

I've submitted the page to make sure the plugin is working; it is. Essentially its just going to the next part of the form without validation the current part

As an example

HTML

<form id = "form1" action = "backend.php" method = "post">
<label for "phone">First Name </label>
    <input type = "text" name = "fName" placeholder = "First Name..." class = "required" id = "fName" />
<button id = "btn" type = "button" class = "buttonnav next">next</button>
</form>

Javascript

$('#btn').click( function() { $("#form1").validate();});

Upvotes: 9

Views: 44239

Answers (1)

Sparky
Sparky

Reputation: 98738

If you're using the jQuery Validate plugin, with your code, the plugin is not initialized until after the button is clicked. If the plugin is not initialized, then there's no validation.

$('#btn').click( function() { $("#form1").validate();});

Instead, .validate() gets called once on DOM ready to initialize the plugin on the form.

If you want to test the form at any time after initialization, you would use the .valid() method.

$(document).ready(function () {

    $('#form1').validate({ // initialize plugin
        // your options
    });

    $('#btn').click( function() { 
        $("#form1").valid();  // test the form for validity
    });

});

I have no idea how you've set up each part to to interact with each other or what other code is being used. Based on your OP alone, here is a working example using my answer above.

DEMO: http://jsfiddle.net/pqVJM/

$(document).ready(function () {

    $('#form1').validate();

    $('#btn').click(function () {
        if ($("#form1").valid()) {
            alert('hello - valid form');
        }
    });

});

Upvotes: 21

Related Questions