Correct validation of email address in compliance with the RFCs is not something that can be achieved with a one-liner regular expression. An article with the best solution I've found in PHP is What is a valid email address?. Obviously, it has been ported to Java. I think the function is too complex to be ported and used inI think the function is too complex to be ported and used in JavaScript. JavaScript/node.js port: https://www.npmjs.com/package/email-addresses.
A good practice is to validate your data on the client, but double-check the validation on the server. With this in mind, you can simply check whether a string looks like a valid email address on the client and perform the strict check on the server.
Here's the JavaScript function I use to check if a string looks like a valid mail address:
function looksLikeMail(str) {
var lastAtPos = str.lastIndexOf('@');
var lastDotPos = str.lastIndexOf('.');
return (lastAtPos < lastDotPos && lastAtPos > 0 && str.indexOf('@@') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);
}
Explanation:
lastAtPos < lastDotPos
: Last@
should be before last.
since@
cannot be part of server name (as far as I know).lastAtPos > 0
: There should be something (the email username) before the last@
.str.indexOf('@@') == -1
: There should be no@@
in the address. Even if@
appears as the last character in email username, it has to be quoted so"
would be between that@
and the last@
in the address.lastDotPos > 2
: There should be at least three characters before the last dot, for example[email protected]
.(str.length - lastDotPos) > 2
: There should be enough characters after the last dot to form a two-character domain. I'm not sure if the brackets are necessary.