There are many regexes which can be used to validate email address, but most of them aren't compatible with non-ASCII characters. Once an email address contains non-ASCII characters like 'Rδοκιμή@παράδειγμα.δοκιμή' or '管理员@中国互联网络信息中心.中国', they can't recognize it correctly. How to construct a regex which is used to validate email address and compatible with non-ASCII characters?
According to this source, JavaScript, which does not offer any Unicode support through its RegExp class, does support \uFFFF for matching a single Unicode code point as part of its string syntax.
So, in order to define matches for Unicode characters, a set of \uXXXX symbols should be created. Plugin listed here enables creation of Unicode regular expressions and can be used to define Unicode regular expressions while using XRegExp JavaScript library.
Here is the function, which tests for valid ASCII email address:
/**
* Checks if string contains valid email address as described
* in RFC 2822: http://tools.ietf.org/html/rfc2822#section-3.4.1
* This function omits the syntax using double quotes and square brackets
* @return {Boolean} True, if test succeeded.
*/
String.prototype.checkEmail = function()
{
var reEmail = /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
return reEmail.test(this);
}
// Usage example
alert( "[email protected]".checkEmail() ); // true
alert( "invalid_email.com".checkEmail() ); // false
In order to make it work for Unicode strings, one can include XRegExp library and use \\p{L} instead of a-z. Here is the complete code:
<!DOCTYPE html>
<html>
<head>
<script src="xregexp-all-min.js"></script>
<script>
/**
* Checks if string contains valid email address as described
* in RFC 2822: http://tools.ietf.org/html/rfc2822#section-3.4.1
* This function omits the syntax using double quotes and square brackets
* @return {Boolean} True, if test succeeded.
*/
String.prototype.checkEmailX = function()
{
var reEmail = XRegExp("^[\\p{L}0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[\\p{L}0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?$");
return reEmail.test(this);
}
alert( "true = " + "Rδοκιμή@παράδειγμα.δοκιμή".checkEmailX() ); // true
alert( "true = " +"管理员@中国互联网络信息中心.中国".checkEmailX() ); // true
alert( "true = " +"[email protected]".checkEmailX() ); // true
alert( "false = " +"test_test.am".checkEmailX() ); // false
alert( "true = " +"test@ράδ.am".checkEmailX() ); // true
</script>
</head>
<body>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With