Reputation: 75
I'm using this regular expression
^(?=.{0,150}$)\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
for validating Email Addresses. when I Enter this Email Address : konstinkö[email protected]
. It is working using Regular expression validator(it is showing InValidEmail Address), but when validating in C# code it is not working(taking it as validEmail Address)
return System.Text.RegularExpressions.Regex.IsMatch(
strEmailAddress,
@"^(?=.{0,150}$)\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",
System.Text.RegularExpressions.RegexOptions.IgnoreCase
);
Upvotes: 0
Views: 1608
Reputation: 146
If I understand your problem you want the address: konstinkö[email protected] to fail validation because it contains Unicode characters. Your regex uses the \w character class which by default matches any word characters, this includes any Unicode characters defined as letters.
You can force \w to be just [a-zA-Z_0-9] by specifying RegexOptions.ECMAScript you code becomes:
return System.Text.RegularExpressions.Regex.IsMatch(
strEmailAddress,
@"^(?=.{0,150}$)\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",
System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.RegexOptions.ECMAScript
);
Alternatively you could replace the \w with [a-zA-Z_0-9] which would have the same effect.
Upvotes: 1
Reputation: 2639
I think a better solution would be using the System.Net.Mail.MailAddress class to validate the email address.
Try using the following code:
try {
MailAddress addr = new System.Net.Mail.MailAddress(email);
return true;
}
catch {
return false;
}
UPDATE Regex solution:
bool d = Regex.IsMatch("konstinkö[email protected]", @"^([\p{L}\.\-\d]+)@([\p{L}\-\.\d]+)((\.(\p{L}){2,63})+)$", RegexOptions.IgnoreCase);
Works for me.
Upvotes: 0
Reputation: 31
Try to use this one:
Regex.IsMatch(strEmailAddress, @"^[\\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])?$", RegexOptions.IgnoreCase);
it will admit non ASCII character
Upvotes: 0
Reputation: 311
End you Regex with $
as an example see this.
http://www.dotnetperls.com/regex-match
Upvotes: 0