I'm trying to create a regular expression to validate any email, I wrote the expression below, but it is not working as expected:
var parse_email = /^[a-z0-9.]+@[a-z0-9]+\.[a-z]+\.([a-z]+)?$/i;
What I expected from each section:
-
[a-z0-9.]+
- part before@
of the email, name of the user; -
@
- obligatory character at arroba; -
[a-z0-9]+
- part after@
of the email, name of the provider; -
\.
- dot character after provider name; -
[a-z]+
- usually where.com
is placed; -
\.
- dot character after.com
, should only be mandatory if there is for example a.br
or abbreviation of any other country at the end of the email; -
([a-z]+)?
- usually where the abbreviation of the country is placed.
How I tested the expression:
var espacos = ' ';
var parse_email = /^[a-z0-9.]+@[a-z0-9]+\.[a-z]+\.[a-z]?$/i;
console.log("[email protected]" + espacos.substring("[email protected]".length) + parse_email.test("[email protected]"));
console.log("[email protected]" + espacos.substring("[email protected]".length) + parse_email.test("[email protected]"));
console.log("[email protected]" + espacos.substring("[email protected]".length) + parse_email.test("[email protected]"));
console.log("foo.bar@gmail." + espacos.substring("foo.bar@gmail.".length) + parse_email.test("foo.bar@gmail."));
console.log("foo.bar@gmailcom" + espacos.substring("foo.bar@gmailcom".length) + parse_email.test("foo.bar@gmailcom"));
console.log("foo.bargmail.com" + espacos.substring("foo.bargmail.com".length) + parse_email.test("foo.bargmail.com"));
console.log("@gmail.com" + espacos.substring("@gmail.com".length) + parse_email.test("@gmail.com"));