[jQuery] Form Validation
[jQuery] Form Validation
Hello, I am using a few plugins together for AJAX forms and
validation. I have validation on the name and phone fields. If you add
a class of required to the fields, the validation plugin will
automatically validate them. If you want to do more advanced
validation you have to tell it so.
I have the below code and if I don't if I fill out the form but put
non integer values in the phone number field it will tell me to put a
valid number. But if I click on submit a second time it will let the
form post. Even though I did not fill in a valid phone number. What am
I doing wrong?
$(document).ready(function() {
$.validator.addMethod("phone", function(ph, element) {
if (ph == null) {
return false;
}
var stripped = ph.replace(/[\s()+-]|ext\.?/gi, "");
// 10 is the minimum number of numbers required
return ((/\d{10,}/i).test(stripped));
}, "Please enter a valid phone number");
$("#post_form").validate({
rules: {
phone: {
required: true,
phone: true
}
}
});
$('#post_form').submit(function(event){
event.preventDefault(); // cancel the default action
var form = this;
var data = {}
data.name = $(form).find('input[@name=name]').val();
data.email = $(form).find('input[@name=email]').val();
data.phone = $(form).find('input[@name=phone]').val();
data.comments = $(form).find('input[@name=comments]').val();
// suppose our django app called 'testapp'
$.post("/user/scheduleshowing/T33432123/",
data,
function(responseData) {
$("#fade").fadeOut("slow");
$("#done").html('<p class="bold">Thank you for your interest.
An associate will contact you shortly.');
},
"json"
);
});
});