1

I have the following code for Email ID validation. I am using the Regular expression to do it. However the following email Id is coming as invalid.

test_@gmail.com

What should be changed in the Regular expression so it passes the email Id (test_@gmail.com)

 public static bool IsValidEmail(string strIn)
        {
            invalid = false;
            if (String.IsNullOrEmpty(strIn))
                return false;

            // Use IdnMapping class to convert Unicode domain names. 
            try
            {

                strIn = Regex.Replace(strIn, @"(@)(.+)$", DomainMapper);

            }
            catch (Exception e)
            {
                Utility.writeToLogFile(String.Format("Error while validating the Email Address {0}. Error Code.e", strIn.ToString(), e));
                return false;
            }

            if (invalid)
                return false;

            // Return true if strIn is in valid e-mail format. 
            try
            {
                return Regex.IsMatch(strIn,
                      @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                      @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
                      RegexOptions.IgnoreCase);


            }
            catch (Exception e)
            {
                Utility.writeToLogFile(String.Format("Error while validating the Email Address {0}. Error Code.e", strIn.ToString(), e));
                return false;
            }
        }
NewUnhandledException
  • 733
  • 2
  • 10
  • 34
  • 3
    Please have a look at the following question and it's accepted answer which was provided by @Alex (the easiest around, let Microsoft do the work if they already did it): http://stackoverflow.com/questions/5342375/c-sharp-regex-email-validation (Btw, please make sure the question you're about to ask doesn't already exist) – Eduard Dumitru Feb 26 '13 at 09:31
  • 2
    Also (and this is just a recommendation): You should try to respect the "Pascal-Case convention" embraced by C# which amongst other things states that method names whould always be capitalized: `Utility.writeToLogFile` should be `Utility.WriteToLogFile`. You understand of course that there's nothing wrong with your code if you don't respect the convention. It's just a good thing if you do. – Eduard Dumitru Feb 26 '13 at 09:37
  • +1 for the Respect should you the "Pascal-Case convention". – NewUnhandledException Feb 26 '13 at 16:33

1 Answers1

1

Your regex is failing for

test_@gmail.com

because the part (?<=[0-9a-z])@ requires explicitly a letter or a digit before the "@".

For a solution I suggest also this answer, like Eduard Dumitru in his comment.

Community
  • 1
  • 1
stema
  • 90,351
  • 20
  • 107
  • 135