19 Aug 2010

ASP.NET MVC Email Validation Attribute using Regular Expression

You want MVC 2 / 3 to automatically validate user-submitted email addresses? Stick the following class in your project:
using System.ComponentModel.DataAnnotations;

public class EmailValidationAttribute: RegularExpressionAttribute
{
    public EmailValidationAttribute() : base(@"^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-zA-Z0-9]{1}[a-zA-Z0-9\-]{0,62}[a-zA-Z0-9]{1})|[a-zA-Z])\.)+[a-zA-Z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$") {  }
}

Then you can use it on your model / model-metadata like this:
[EmailValidation(ErrorMessage="Not a valid Email Address")]
public string Email { get; set; }

NOTE: The regex is STRONG AND GOODLY because I found a definitive source. Scott Gu has a similar solution but for once THE MIGHTY GU HAS LET US DOWN. :p

1. His regex is incomplete and wrong (doesn't allow upper-case first part to the address)
2. His blogpost comments are disabled so I can't let him know about it.

NAUGHTY GU!

14 comments:

  1. Anonymous12:49 pm

    Thanks

    ReplyDelete
  2. Anonymous2:07 pm

    SWEET!

    ReplyDelete
  3. Replies
    1. Anonymous8:33 am

      Ha ha I see what you did there

      Delete
  4. Chris Williamson Hobbis12:52 pm

    Hey nice one James! Shall be using it in my current proj.

    ReplyDelete
  5. Thanks James. Worked perfectly and I will be using it in my current project.

    If only you were in Belfast then you could train me!

    ReplyDelete
  6. Anonymous11:27 pm

    Thanks for this code! -Bill

    ReplyDelete
  7. Anonymous9:29 pm

    Thanks....

    ReplyDelete
  8. thanks! it helped a lot!

    ReplyDelete
  9. Anonymous7:40 pm

    Thanks! Good one.

    ReplyDelete
  10. Anonymous2:11 am

    Thanks!

    ReplyDelete
  11. Anonymous11:59 am

    great thanks

    ReplyDelete
  12. Anonymous12:09 am

    Sorry,it didn't work for me. Does it depend on a particular js validator

    ReplyDelete
  13. the last guy12:19 am

    me again - it looks like IE 8 issue.

    ReplyDelete

Comments are very welcome but are moderated to prevent spam.

If I helped you out today, you can buy me a beer below. Cheers!