javascript

Regex for email validation in Javascript

The best way to validate an email address using javascript is by using regular expressions and check it against the email.

function email_validator(my_email) {
    var email_pattern = /^(([^<>()[]\.,;: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,}))$/;
    if (email_pattern.test(my_email)) {
        console.log("Email is Valid");
    } else {
        console.log("Email is Invalid");
    }
}

email_validator("[email protected]"); // -> logs - Email is Valid
email_validator("test.com"); // -> logs - Email is Invalid

In the code example, we are validating two emails using the email_validator() function which is using regular expressions to validate the email address. If the email is valid it will log "Email is valid" and for an invalid email address, it will log "Email is Invalid".

LIVE DEMO

Was this helpful?