-2

The below regex is not validating if the email address has a full stop at the end. E.G test@gmail.com. If I pass this email address as the strEmail parameter to the IsValidEmailAddress function, the function will return true. It should return false.

const string MatchEmailPattern = @"(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
                        + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
                        + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
                        + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})";

private bool IsValidEmailAddress(string strEmail)
{
    System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(strEmail.Trim().ToLower(), MatchEmailPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);

    if (!match.Success)
    {
        return false;
    }
    return true;
}

I would greatly appreciate suggestions on how to handle the trailing full stop.

MadDev
  • 1,130
  • 1
  • 13
  • 29

1 Answers1

4

You need to add the "end of string" token to your regex pattern

const string MatchEmailPattern = @"(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
                + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
                + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
                + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";

...and to make it to the end, add also the "start of string" token:

const string MatchEmailPattern = @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
                    + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
                    + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
                    + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
janwin
  • 54
  • 5