Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();});
like image 307
Art Taylor Avatar asked Mar 15 '13 17:03

Art Taylor


1 Answers

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');
        }
    });

});
like image 185
Sparky Avatar answered Nov 20 '22 06:11

Sparky