0

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öpet@gmail.com . 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
);
user3270152
  • 75
  • 2
  • 11

4 Answers4

1

If I understand your problem you want the address: konstinköpet@gmail.com 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.

Reubene
  • 146
  • 2
0

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

ste
  • 31
  • 9
  • It should not admit Non-Ascii Character, I need a regular expression for not accepting Non-Ascii characters ,Special Characters and SPaces – user3270152 Feb 20 '14 at 07:24
  • You have to add this condition: [^\x00-\x7F]. – ste Feb 20 '14 at 15:19
  • @user3270152 `ö` is not ASCII. Maybe I misunderstood the problem. In any case, in .NET/C#, [\w includes non-ASCII Unicode](http://stackoverflow.com/questions/2998519/net-regex-what-is-the-word-character-w) – user2864740 Feb 20 '14 at 16:27
0

End you Regex with $ as an example see this. http://www.dotnetperls.com/regex-match

SMI
  • 303
  • 1
  • 6
  • 22
0

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öpet@gmail.com", @"^([\p{L}\.\-\d]+)@([\p{L}\-\.\d]+)((\.(\p{L}){2,63})+)$", RegexOptions.IgnoreCase);

Works for me.

Eliran Pe'er
  • 2,569
  • 3
  • 22
  • 33