Ilja Ilja - 3 months ago 23
Javascript Question

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
. Could anyone suggest a solution please.


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