Ilja
Ilja

Reputation: 46519

Check if correct e-mail was entered

I have a field for users to write their e-mail address in. It is optional, so I need to first check if something was entered in the field, if nothing was entered then do nothing, but if something was entered than check if it is an e-mail.

Right now I'm at this point

var email = $("input#sc_email").val();  
if (email == "") {                
    // If e-mail field is empty do nothing
} else {                          
     // If something was entered
    // [CODE HERE] Check if valid e-mail was entered, if not show error message
    $("label#email_error").show(); //error message
    $("input#sc_email").focus();   //focus on email field
    return false;  
} 

I'm not even sure if that is right, but I think it is. Right now I need help with gaps in code, I marked them as [CODE HERE]. Could anyone suggest a solution please.

Upvotes: 9

Views: 27470

Answers (3)

Asghar
Asghar

Reputation: 11

I would recommend validation both at client side and at server side, you could simply use this code:

alert(/\S+@\S+\.\S+/.test('asdasd@[email protected]'));
alert(/\S+@\S+\.\S+/.test('[email protected]'));

but importantly, use server side validation and methodology, like sending click-link-mail, to verify your client email address or mailing random number etc.

Upvotes: 1

Connell
Connell

Reputation: 14421

You could use regular expressions to validate the email address in JavaScript.

function validateEmail(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);
}

This will, however, only validate that it is a valid email address formatted string. [email protected] would be valid, even if no-one actually has that email address.

Have a look at this question.

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337637

You could use the jQuery validate plugin for this, but if you only want to check the validity of an email address in one field, that is a little bit of overkill.

Instead, the regular expression in the function below will make sure the format of the email address is correct, should a value have been entered.

var email = $("input#sc_email").val();  

if (email !== "") {  // If something was entered
    if (!isValidEmailAddress(email)) {
        $("label#email_error").show(); //error message
        $("input#sc_email").focus();   //focus on email field
        return false;  
    }
} 

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
};

Upvotes: 23

Related Questions