memyselfandmyiphone
memyselfandmyiphone

Reputation: 1110

Ajax email address validator

Currently the below script works brillantly checking the database using ajax to see if the email address has been used before. My question is how do I stop it checking the database until it is a fully defined EMAIL address?

Form field

<label for="email">Email: *&nbsp;</label><br/>
     <input id="username" name="username" type="email" value="" onblur="return check_username();" />

AJAX script

<script type="text/javascript">

$(document).ready(function() {
    $('#Loading').hide();    
});

function check_username(){

    var username = $("#username").val();
    if(username.length > 2){
                $.post("../script/check_username_availablity.php", {
            username: $('#username').val(),
        }, function(response){
            $('#Info').fadeOut();

            setTimeout("finishAjax('Info', '"+escape(response)+"')", 450);
        });
        return false;
    }
}

function finishAjax(id, response){

  $('#'+id).html(unescape(response));
  $('#'+id).fadeIn(1000);
} 

</script>

Upvotes: 0

Views: 1114

Answers (2)

Chris Montgomery
Chris Montgomery

Reputation: 2354

see http://jsfiddle.net/cmontgomery/gEL7n/

very similar to what ialencar posted:

isValidateEmail = function(email) { 
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
} 

check_username = function() {
    var username = $("#username").val();
    if(isValidateEmail(username)) {
        $("#username-error").html("");
        console.log("ajax request...");
    } else {
        $("#username-error").html("invalid email address");
    }
}

Upvotes: 0

izilotti
izilotti

Reputation: 4927

Instead of if(username.length > 2){... use something like:

if (/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\
".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(username.val())) {...

Upvotes: 1

Related Questions