Click here to Skip to main content
15,894,343 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Friends,

I have two expression to validate the email ID
#1 "^[a-zA-Z0-9_\\+-]+(\\.[a-zA-Z0-9_\\+-]+)*@[a-zA-Z0-9-]
+(\\.[a-zA-Z0-9-]+)*\\.([a-zA-Z]{2,4})$"

#2 "Regex.IsMatch(viewmodel.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$)"


The Problem is #1 validation expression always successful. But #2 validation expression is fail in some case.

1. why expression #2 is fail
2. Which expression ( #1 and #2) is best to use

Please help in this issue.

Thanks,
Shanmuga Raja

What I have tried:

I dont Know why "Regex.IsMatch(viewmodel.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$)" gets fail.
Posted
Updated 12-Sep-22 17:42pm

1 solution

I dont Know why "Regex.IsMatch(viewmodel.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$)" gets fail.

Mismatched brackets.
The expression you pass to Regex contains a spurious ')' at the end which the expression evaluator doesn't understand.

But...I wouldn't use a regex for this: you can get long TLDs which don;t fit in three of four characters: ".museum" for example, so restricting TLD to 2 or 4 characters is a bad idea. Also, a domain can contain '.' as either part of the name: "mobile.mydomain.com" or part of the "country code": "mydomain.co.uk" so you need to allow for that.

Microsoft recommend using the MailAddress Class (System.Net.Mail)[^] constructor to check for valid names: How to: Verify that Strings Are in Valid Email Format[^] - see the NOTE section.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900