check if form validation is true

javascript, jquery, jquery-validate

Solution

You can call the valid() method of jquery validation. Like

if($('#form').valid())

Actually you can declare the validate function when the html page is loaded and just check whether it's valid or not at the time of submit

$(document).ready(function(){

$('#form').validate(rules...messages...);

In case of rules & messages use:-

  rules: {
            name: {
               required: true  
            },
            email: {
                required: true,
                email: true
                    },
            phone: {
                required: true,
                phone: true                       }
                },
        messages: {
            name: { required : "Please let us know who you are."},
           email: {required : "A valid email will help us get in touch with you.",email : "A valid email will help us get in touch with you."},
            phone: {required:"Please provide a valid phone number.",phone:"Please provide a valid phone number."}
        }

It's a good practice and in case of phone numbers, you've misspelled required

$('#form').submit(function(evt) {
    evt.preventDefault();

    .....

    if( $('#form').valid() ) {
       //submit the form via ajax
    } else {
       //show errors
    }
 });

});

And I think you know than you've to add the name attribute of each input field:-

 <input type="text" name="email" />

Problem

Hello i have a form that i want to run through form validation and then submit. How can i check if the following function returns true to know that everything has been validated and then submitted? I created a fiddle to test http://jsfiddle.net/WHGq2/ MODIFIED CODE ``` <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script> <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script> <script type="text/javascript"> $(function(){ $("#form").validate({ debug: false, rules: { name: "required", email: { required: true, email: true }, phone: { equired: true, phone: true } }, messages: { name: "Please let us know who you are.", email: "A valid email will help us get in touch with you.", phone: "Please provide a valid phone number.", } }) $('#form').submit(function(e){ // Stop the form actually posting e.preventDefault(); // I want to be able to do the check here if the form has passed validation if( $(this).valid() ) { // Stop the form actually posting // Send the request $.post('/submit.php', { name: $('#name').val(), email: $('#email').val(), phone: $('#phone').val(), message: $('#message').val() }, function(d){ alert("Thank you for submitting your request someone will contact your shortly."); }); } }); }); </script> ```

Original source