2

I have been working on a simple email validation. But it doesn't work.

Any ideas why it isn't working? Am I doing something wrong or should I structure my code in some other way?

I have done a function like this:

function IsEmail(email) {
    var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if(!regex.test(email)) {
        return false;
    } else {
        return true;
    }
}

and after that I'm calling that function in my setupRegistration function.

My JS looks like this:

function doOutputMessage(type, message){
    $("#outputMessage").html("");
    $("#outputMessage").removeClass();
    $("#outputMessage").hide();
    if(type == "error") {
        $("#outputMessage").addClass("error").fadeIn("fast");
    } else if(type == "success") {
        $("#outputMessage").addClass("success").fadeIn("fast");
    }

    $("#outputMessage").text(message);
    $("#outputMessage").show();
}

function setupRegistration(){

    $("#signupWrapper").on("click", "#regUser", function(){
        var username = $("input[name='username']").val();
        var email = $("input[type='email']").val();
        var password = $("input[type='password']").val();

        if(username == ""){
            doOutputMessage("error", "Fill in your desired username!");
        }

        if(email == ""){
            doOutputMessage("error", "Fill in your email!");
        }

        if(IsEmail(email)==false){
            doOutputMessage("error", "mailen är fel förfan");
        }

        if(password == ""){
            doOutputMessage("error", "Fill in your desired password!");
        }

        if(username != "" && email != "" && password != ""){
            ajaxCall(username, email, password);
        }   
    });
}

function IsEmail(email) {
    var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if(!regex.test(email)) {
       return false;
    }else{
       return true;
    }
}


function ajaxCall(username, email, password){
    $.ajax({
        type: 'POST',
        url: '../register.php',
        data:   {
            'username' : username,
            'email' : email,
            'password' : password,
        },
        success: function(data) {
            if(data.exists){
                doOutputMessage("error","That Username is allready taken.");
            } else if(data.inserted) {
               doOutputMessage("success","You have successfully been registered!");
            }else {
                doOutputMessage("error","Something went wrong, try again later.");
            }
        }
    });
}

$(document).ready(function(){
    setupRegistration();
});


function regSubmit(){

    clearErrorMessages();

    var username = $("#regForm #username").val();
    var email = $("#regForm #email").val();
    var password = $("#regForm #password").val();

    if(username == ""){
        showValidationMessage("#regForm #error_username", "Fill in your desired username!");
    }

    if(email == ""){
        showValidationMessage("#regForm #error_email", "Fill in your email!");
    }

    if(password == ""){
        showValidationMessage("#regForm #error_password", "Fill in your desired password!");
    }

    if(username != "" && email != "" && password != ""){
        $.ajax({
            url:    'regLogin.code.php',
            type:   'POST',
            data:   {
                    'action'    :   'register',
                    'username'  :   username,
                    'email'     :   email,
                    'password'  :   password
                    },
            success: function(data, status){
                console.log(data);
                if(data == "exist"){
                    showValidationMessage("#regForm  #error_general", "A user with that username or password already exists!");
                }else if(data == "illegal"){
                    showValidationMessage("#regForm  #error_general", "Your username contains illegal characters!");
                }
                else if(data == "true"){
                    showValidationMessage("#regForm  #success", "Success!");
                    setTimeout(function(){
                        window.location.replace("/admin/inside/");
                    }, 1000);
                }
            },
            error: function(xhr, desc, err){
                showValidationMessage("#regForm  #error_general", "Something went wrong, please try again");
            }
        });
    }
}
Peter
  • 1,674
  • 4
  • 27
  • 44
Jonas Alvarson
  • 411
  • 2
  • 6
  • 20

4 Answers4

1

@Mario-Chueca is right. Your code is mostly working correctly, however, you are making an Ajax call regardless if the email is correct and as a result the error message is not shown. You should only make the ajax call when the specified email is valid:

if(username != "" && email != "" && password != "" && IsEmail(email)){
    ajaxCall(username, email, password);
}  

I have included a code sample below to show that your email validation (without Ajax call) is working. I have included the if(!IsEmail(email){ fix suggested by @Abdulla and I also also added a more complex regular expression from this post.

function IsEmail(email) {
  //var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  //More advanced regex to valid 99.99% of most emails in use, see https://stackoverflow.com/questions/46155/validate-email-address-in-javascript
  var regex = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
  if (!regex.test(email)) {
    return false;
  } else {
    return true;
  }
}

function doOutputMessage(type, message) {  
  $("#outputMessage").html("");
  $("#outputMessage").removeClass();
  $("#outputMessage").hide();
  if (type == "error") {
    $("#outputMessage").addClass("error").fadeIn("fast");
  } else if (type == "success") {
    $("#outputMessage").addClass("success").fadeIn("fast");
  }

  $("#outputMessage").text(message);
  $("#outputMessage").show();
}


//if (IsEmail('john.doe@stackoverflow.com')) {

//  doOutputMessage('success', 'valid email')
//}



if (!IsEmail('john.doe#stackoverflow.com')) {

  doOutputMessage('error', 'invalid email')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outputMessage">Test</div>
Community
  • 1
  • 1
Alex
  • 21,273
  • 10
  • 61
  • 73
  • This worked. Added && IsEmail(email) so the ajaxCall werent made even if the mail was wrong. Thanks for the help everyone. Im pretty new to jquery, but im learning everyday. The hard part is too structure the code in a goodway. It feels like im just putting my code randomly and dont have any structure. But maybe i will learn to do this as i code? – Jonas Alvarson Oct 28 '15 at 10:09
1

Use some of the advices from before, but change this too, the error doesn't stop the ajax call:

var error_email=false;
if(!IsEmail(email)){
    error_email=true;
    doOutputMessage("error", "mailen är fel förfan");
}

if(password == ""){
    doOutputMessage("error", "Fill in your desired password!");
}

if(username != "" && email != "" && password != "" && !error_email){
    ajaxCall(username, email, password);
} 
Mario Chueca
  • 116
  • 7
0

remove false in here

if(!IsEmail(email){

and regex should be

regex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

Live DEMO

How to Find or Validate an Email Address

Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
0

please try:

function IsEmail(email){
    var reg = /^[a-zA-Z0-9\.\-\+]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/
    return reg.test(email)
}
YonF
  • 641
  • 5
  • 20