Trouble with jquery validator and AJAX form submission
I'm creating an AJAX form and wanting to run some client-side validation using jquery.validator (
http://bassistance.de/jquery-plugins/jquery-plugin-validation/). It works as I move through the form but when I hit the submit button, the AJAX portion will submit the form regardless of the results of the validation. Is there a way to prevent the AJAX handler from submitting if validation fails?
Here's my form code:
- <form id="form1" action="" method="post">
- <label for="TxtName">Name</label>
- <input type="text" name="TxtName" id="TxtName" class="txtinput"/>
- <br />
- <div class="small">
- <label for="TxtEmail">Email</label>
- <input type="text" name="TxtEmail" id="TxtEmail" class="txtinput" style="width:241px; height:35px;"/>
- </div>
- <label for="TxtPhone">Phone</label>
- <div class="small" style="padding-left:6px">
- <input type="text" name="TxtPhone" id="TxtPhone" class="txtinput" style="width:241px; height:35px;"/>
- </div>
- <label for="TxtMessage">Message</label>
- <textarea name="TxtMessage" rows="20" cols="20" id="TxtMessage" class="txtmessage"></textarea>
- <input type="submit" name="submit" value="Submit" id="btn-form" class="button"/>
- </form>
and here's the javascript for the validator:
- //initiate validator on load
- $(function() {
- // validate contact form on keyup and submit
- $("#form1").validate({
- //set the rules for the field names
- rules: {
- TxtName: {
- required: true,
- minlength: 2
- },
- TxtEmail: {
- required: true,
- email: true
- },
- TxtMessage: {
- required: true,
- minlength: 2
- },
- },
- //set messages to appear inline
- messages: {
- TxtName: "Please enter your name",
- TxtEmail: "Please enter a valid email address",
- TxtMessage: "Please enter your message"
- }
- });
- });
followed by the javascript for the AJAX submission:
- //engage on the page load
- $(function() {
- //trigger ajax on submit
-
- $('#form1').submit( function(){
- //hide the form
- $('#form1').hide();
- //show the loading bar
- $('.loader').append($('.bar'));
- $('.bar').css({display:'block'});
- //send the ajax request
- $.get('mail.php',{name:$('#TxtName').val(),
- email:$('#TxtEmail').val(),
- phone:$('#TxtPhone').val(),
- comment:$('#TxtMessage').val()},
- //return the data
- function(data){
- //hide the graphic
- $('.bar').css({display:'none'});
- $('.loader').append(data);
- });
- //stay on the page
- return false;
- });