hejto
hejto

Reputation: 53

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, e.g., 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 å (e.g. å[email protected]). 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?

Upvotes: 5

Views: 5158

Answers (2)

Bharath theorare
Bharath theorare

Reputation: 554

The characters you mentioned (ø, å or å[email protected]) 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,})

Upvotes: 0

Manfred Radlwimmer
Manfred Radlwimmer

Reputation: 13394

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

Upvotes: 4

Related Questions