MVC Regex Phone Numbers and Emails

This is just a quick bit on Phone Numbers and Emails in MVC.  Well, at least MVC3.  The [DataType(DataType.PhoneNumber, ErrorMessage = “You must provide a valid phone number.”)] and [DataType(DataType.EmailAddress, ErrorMessage = “You must provide a valid email address.”)] apparently does not perform the actual validation for you.  Don’t fret though, you can add the RegularExpression annotation to it.

Here are two examples, you can use any regex expression, these worked for my needs.  I also left some other annotations in there.

[Required(AllowEmptyStrings = false, ErrorMessage = "You must provide a supervisor email.")]
[StringLength(50, ErrorMessage = "A supervisor email cannot exceed 50 characters.")]
[Display(Name = "Supervisor Email")]
[DataType(DataType.EmailAddress, ErrorMessage = "Please enter a valid supervisor email address.")]
[RegularExpression("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$", ErrorMessage = "You must provide a valid supervisor email address.")]
public string SupervisorEmail { get; set; }

[Required(AllowEmptyStrings = false, ErrorMessage = "You must provide your home phone number.")]
[Display(Name = "Home Phone")]
[DataType(DataType.PhoneNumber, ErrorMessage = "You must provide a proper phone number.")]
[RegularExpression("^\\D?(\\d{3})\\D?\\D?(\\d{3})\\D?(\\d{4})$", ErrorMessage = "You must provide a proper phone number.")]
public string HomePhone { get; set; }
Advertisements

About SheldonS

Web developer for over 15 years mainly with Microsoft technologies from classic ASP to .NET 4. Husband, father, and aspiring amateur photographer.

Posted on November 26, 2012, in MVC, Regular Expression and tagged , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: