views:

38

answers:

1
+2  Q: 

Validating Form

How to validate form fields on submit button using jquery?

+2  A: 

jQuery.validate plugin is the best solution I've found.

All you have to do is give the inputs the class "required" and then call .validate() on the form in your document.ready call e.g.

$(function() { 
    $('#idofyourform').validate();
});

You can also do email and other types of validation using the same method. The plugin is also extensible for your own rules.

Remember you will also need to validate any data server side.

Edit: Response to comment

To validate only when the form is submitted add the following option:

$("#idofyourform").validate({
   onsubmit: true,
   onkeyup: false,
   onfocusout: false,
   onclick: false
})

Have a read of the options for more detail.

Rob Stevenson-Leggett
I know that one ..but how do I use that to validate only when form is submitted.
yogsma
Do you mean you don't want inline validation? Only when the user clicks submit? If so see expanded answer.
Rob Stevenson-Leggett
Somehow it is not working.
yogsma
Is there an error?
Rob Stevenson-Leggett
Ah, sorry I've misremembered this. It's the other way around. I've editted my code to reflect this.
Rob Stevenson-Leggett
It doesn't throw any error ..here is my code$('#formname').validate({onsubmit:true,onkeyup:false,onclick:false});
yogsma
You haven't got onfocusout:false is it still validating when you leave a textbox?
Rob Stevenson-Leggett
I added that too. It doesn't validate in any way. Do you have a working example?
yogsma
You do have the class "required" or "email" on the fields?
Rob Stevenson-Leggett
Yes, I do have class "required" on the fields
yogsma