views:

63

answers:

3

I am trying to attach the validation on a button click. I have:

  <script>
 $().ready(function() {
//
    $("#btnAdd").click(function() { 

        $("#myForm").validate({                     
        // $("#crap").rules("add", {required: true,  messages: {required:"Required input"} });
        rules: { crap: "required" },
        messages: { crap: "required field"}
        // $("#myForm").validate();
        });   

});

}); 
</script>

<form method="post" id="myForm" name="myForm">
<input type="text" name="crap" id="crap" class="required" />
<br />
<input type="button" name="btnAdd" id="btnAdd" value="add" />
</form>

now, if i change btnAdd to a submit type, it works. otherwise, it won't. how can i call the validation on a button click ? thanks

+1  A: 

validation happens on submit that is why it work..

do you not want to submit the form ?

you could invoke the submit function yourself by chaining the submit call to the validate one ..

$("#myForm").validate({                     
        // $("#crap").rules("add", {required: true,  messages: {required:"Required input"} });
        rules: { crap: "required" },
        messages: { crap: "required field"}
        // $("#myForm").validate();
        }).form(); 

[EDIT] Actually the validate plugin has the form method which triggers the validation, so chain that instead of the submit.. (updated in code above)

http://docs.jquery.com/Plugins/Validation/Validator/form

Gaby
Nice one, weird though that it's called `.form()` on the validator, and `.valid()` on the form/elements
Sander Rijken
Gaby, excellent. thanks.
FALCONSEYE
A: 

The validate() call sets up validation on the form. It validates when the form is submitted. You can call valid() to force validation. See docs and demo

$().ready(function() {
    $("#myForm").validate({                     
        // $("#crap").rules("add", {required: true,  messages: {required:"Required input"} });
        rules: { crap: "required" },
        messages: { crap: "required field"}

    });   
    $("#btnAdd").click(function() {
        if($("#myForm").valid()) { 
            // Submit the form?
        }
    }); 
});
Sander Rijken
A: 

The validate is actually being attached to the form NOT the button. You do not have to put the

   $("#myForm").validate({...});

inside the button click code. The validation gets called on the form submit. A button does not automatically submit a form, but

<input type="submit".../> 

does. That is why the form validation only kicks in when you use a submit input.

If you do need a button for some reason then you should have your button submit the form programmatically.

Vincent Ramdhanie