Phill Healey
Phill Healey

Reputation: 3180

Regular Expression for Email #2

I've got a regular expression that I am using to check against a string to see if it an email address:

@"^((([\w]+\.[\w]+)+)|([\w]+))@(([\w]+\.)+)([A-Za-z]{1,3})$"

This works fine for all the email addresses I've tested, provided the bit before '@' is at least four characters long.

Works:

[email protected]

Doesn't work:

[email protected]

How can I change the regex to allow prefixes of less than 4 characters??

Upvotes: 2

Views: 1411

Answers (6)

Wasabi
Wasabi

Reputation: 506

The little trick used in the validated answer i.e. catching exceptions on

new MailAddress(email);

doesn't seem very satisfying as it considers "a@a" as a valid adress in fact it does't raise an exception for almost any string matching the regex "*.@.*" which is clearly too permissive for example

new MailAddress("¦#°§¬|¢@¢¬|") 

doesn't raise an exception.

Thus I clearly would go for regex matching

This example is quite satisfying

https://msdn.microsoft.com/en-us/library/01escwtf%28v=vs.110%29.aspx

Upvotes: 0

Ken
Ken

Reputation: 1985

I recommend not using a regex to validate email (for reasons outlined here) http://davidcel.is/blog/2012/09/06/stop-validating-email-addresses-with-regex/

If you can't sent a confirmation email a good alternative in C# is to try creating a MailAddress and check if it fails.

If you're using ASP.NET you can use a CustomValidator to call this validation method.

    bool isValidEmail(string email)
    {
        try
        {
            MailAddress m = new MailAddress(email);
            return true;
        }
        catch
        {
            return false;
        }
    }

Upvotes: 0

hoang
hoang

Reputation: 1917

I believe the best way to check a valid email address is to make the user type it twice and then send him an email and challenge the fact that he received it using a validation link.

Check your regex againt a list of weird valid email addresses and you will see regexes are not perfect for email validation tasks.

Upvotes: 2

Kurushimeru
Kurushimeru

Reputation: 35

You can also try this one

^[a-zA-Z0-9._-]*@[a-z0-9._-]{2,}\.[a-z]{2,4}$

Upvotes: -1

Neil Thompson
Neil Thompson

Reputation: 6425

The 'standard' regex used in asp.net mvc account models for email validation is as follows:

@"^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$"

It allows 1+ characters before the @

Upvotes: 3

Ali Shah Ahmed
Ali Shah Ahmed

Reputation: 3333

You can use this regex as an alternative:

^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$

Its description can be found here.

About your regex, the starting part (([\w]+\.[\w]+)+) forces the email address to have four characters at the beginning. Emending this part would do the work for you.

Upvotes: 0

Related Questions