Validate email address against invalid characters
In validating email addresses I have tried using both the EmailAddressAttribute
class from System.ComponentModel.DataAnnotations
:
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
and the MailAddress
class from System.Net.Mail
by doing:
bool IsValidEmail(string email)
{
try {
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == email;
}
catch {
return false;
}
}
as suggested in C# code to validate email address. Both methods work in principle, they catch invalid email addresses like, eg, user@
, not fulfilling the format user@host
.
My problem is that none of the two methods detect invalid characters in the user field, such as æ, ø, or å (eg åge@gmail.com)
. Is there any reason for why such characters are not returning a validation error? And do anybody have a elegant solution on how to incorporate a validation for invalid characters in the user field?
Those characters are not invalid. Unusual, but not invalid. The question you linked even contains an explanation why you shouldn't care.
Full use of electronic mail throughout the world requires that (subject to other constraints) people be able to use close variations on their own names (written correctly in their own languages and scripts) as mailbox names in email addresses.
- RFC 6530, 2012
The characters you mentioned ( ø, å or åge@gmail.com
) are not invalid. Consider an example: When someone uses foreign language as their email id (French,German,etc.), then some unicode characters are possible. Yet EmailAddressAttribute
blocks some of the unusual characters.
You can use international characters above U+007F , encoded as UTF-8
.
space and "(),:;<>@[] characters are allowed with restrictions (they are only allowed inside a quoted string, a backslash or double-quote must be preceded by a backslash)
special characters !#$%&'*+-/=?^_`{|}~
Regex to validate this: Link
^(([^<>()[].,;:s@"]+(.[^<>()[].,;:s@"]+)*)|(".+"))@(([^<>()[].,;:s@"]+.)+[^<>()[].,;:s@"]{2,})
链接地址: http://www.djcxy.com/p/16590.html上一篇: 电子邮件地址的dsv的安全分隔符
下一篇: 根据无效字符验证电子邮件地址