Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Email validation with regex [duplicate]

I want to validate an email with a regex. And the code following shows the regular expression that I've used. The form however does not accept a simple [email protected]. (anystring is an alphabetic).

Am I missing out something?

window.onload = function () {
    document.getElementById("form").onsubmit = validate;
}

function validate() {
    var email = document.getElementsByTagName("input")[6].value;
    var regex = /^\w@\w+\.\w$/;
    if (!regex.test(email)) {
        alert("enter a valid email");
        return false;
    } else return true;
}
like image 409
faisal bhat Avatar asked Sep 17 '15 12:09

faisal bhat


1 Answers

Unless you know for sure that email addresses entered will match that format, you should consider using a regular expression that matches more.

"()<>[]:,;@\"!#$%&'*+-/=?^_`{}| ~.a"@üñîçøðé.com is technically(!) a correct email address. While it may not be a good idea to match all of this craziness, this may be what you are looking for and will match the vast majority of email addresses today:

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

Again, if you are sure your email addresses will be in the format you were going for originally, go with Valinho's answer.

An interesting read about matching email addressses with regular expressions (contains the above regex): http://www.regular-expressions.info/email.html

And the official standard (without unicode madness): https://www.rfc-editor.org/rfc/rfc5322

like image 147
icke Avatar answered Sep 30 '22 07:09

icke