0

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 :-)

  • 3
    ajax is asynchronous - you are returning r before the ajax process completes - you will need to rewrite your code to use callbacks or promises because you wont be able to `return r` from that function – Jaromanda X Nov 09 '15 at 22:20
  • return false doesn't make a whole lot of sense where it is even if it wasn't asynchronous. Returning false prevents the event from occuring, thus making it impossible for the user to enter a valid email address other than through copy/paste and autocomplete. – Kevin B Nov 09 '15 at 22:30
  • If you don't need your method to be asynchronous, a quick fix is to add "async: false" to your ajax call. – Zachary Nov 09 '15 at 22:31
  • 2
    I wish i could downvote comments that suggest awful solutions. – Kevin B Nov 09 '15 at 22:32

1 Answers1

1

checkMail should accept an optional callback, and call it with the result if defined

function checkEmail(callback) {
    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");
        if(callback) {
            callback(false);
        }
    }
    else {
        $.ajax({
            type: "POST",
            url: "index.php?p=jsform&ajaxcall=checkEmail",
            data: {'mail':mail},
            dataType: 'json',
            success: function(res) { 
                if(res) {
                    $("#mail_mess").html("OK");
                    //return true;
                }
                 else {
                    $("#mail_mess").html("Email already Exists!");
                    //return false;
                }
                if(callback) {
                    callback(res);
                }
            }            
        });
    }
}

no need for callback function here

$("#email").on("input", function() {
    checkEmail();
}); 

the fail function defined to avoid repetition because there's now two "false" paths

$("#submitButton").click(function() {
    function fail() {
        $("#form_message").html("<span class='error'>All fields are required</span>");
    }
    if(...) {
        checkEmail(function(r) {
            if (r) {
                sendForm();
            }
            else {
                fail()
            });
    else {
        fail();
    }
});
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87