0

Currently I am using below code to validate email

public static bool IsValidEmail(string email)
        {
            var r = new Regex(@"^([0-9a-zA-Z]([-\.\'\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$");
            return !string.IsNullOrEmpty(email) && r.IsMatch(email);
        }

Now want to validate this "[email protected]" email as valid email id. what change needs to be done in regex?

3
  • 2
    Don't use a regex? Even emailregex.com is wrong some of the time. You could use learn.microsoft.com/en-us/dotnet/api/… instead. Commented Sep 30, 2021 at 6:47
  • @jeremy thanks for the reply, I am looking required change/edit in my Regex to accept "[email protected]" Commented Sep 30, 2021 at 7:36
  • ([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+ That's only matching sub-domains that start and end with an alphanumeric, and therefore must have 2 characters. But I still wouldn't try to "fix" the regex, because a regex is never going to be 100% right. Stop trying to use a hammer for everything, use the right tool. If you want to check if an email is valid, try to send a verification code. Commented Sep 30, 2021 at 7:48

1 Answer 1

3

Using this Regex is not the best way to validate an Email.

But, correcting your Regex to the pattern you asked, it would be like this:

var r = new Regex(@"^([0-9a-zA-Z]([-\.\'\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z\.])+[.a-zA-Z]{2,9})$");

Still insisting on the regex, you can find a more complete pattern in: https://www.ex-parrot.com/pdw/Mail-RFC822-Address.html

I encourage you to use Microsoft documentation for email address as suggested by @Jeremy Lakeman -> https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.mailaddress.trycreate?view=net-5.0

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.