I'm creating a form and I want to validate it in real time. Everythings works in the ajax call, but I have a problem with the returns. This is the code:
function checkEmail() {
var reg_exp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
var mail = $("#email").val();
if (!reg_exp.test(mail) || (mail === "") || (mail === "undefined")) {
$("#mail_mess").html("Enter a valid email address");
return false;
}
else {
var r = '';
$.ajax({
type: "POST",
url: "index.php?p=jsform&ajaxcall=checkEmail",
data: {'mail':mail},
dataType: 'json',
success: function(res) {
r = res;
if(res) {
$("#mail_mess").html("OK");
//return true;
}
else {
$("#mail_mess").html("Email already Exists!");
//return false;
}
}
});
//alert(r);
return r;
}
}
$("#email").on("input", function() {
checkEmail();
});
$("#submitButton").click(function() {
if(... && checkEmail()) {
sendForm();
}
else {
$("#form_message").html("<span class='error'>All fields are required</span>");
}
});
As you can see, I call the function checkEmail() on input change (for the realtime validation) and on submit (all fields check before sending data). The function checkEmail() should return false on invalid email or on already existing email and should return true on valid and non existing email.
Now.. the function works on realtime validation, I get the "non valid", "already exists" or "valid" exactly when I want. The problem is with the returns, because when I return r, it is an empty string (seems like r = res doesn't work). And if I try to uncomment the returns inside the if(res)/else they don't work as well.
I'm sorry about my bad english! Thanks for any help :-)