Category Archives: Regular Expression

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

Date Regex

Yes I do keep forgetting the regular expression to validate a date. At O’Reilly Answer’s I found a nice article by Jan Goyvaerts. Please read the article. The expression that works best for most of my situations is below.

Match m/d/yy and mm/dd/yyyy, allowing any combination of one or two digits for the day and month, and two or four digits for the year:
^(1[0-2]|0?[1-9])/(3[01]|[12][0-9]|0?[1-9])/(?:[0-9]{2})?[0-9]{2}$