RegularExpression Validation in MVC

Some properties of Order require more than a simple presence or length check. For example, you’d like to ensure the Email property of an Order contains a valid, working e-mail address. Unfortunately, it’s practically impossible to ensure an e-mail address is working without sending a mail message and waiting for a response. What you can do instead is ensure the value looks like a working e-mail address using a regular expression:

[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
public string Email { get; set; }

Regular expressions are an effi cient and terse means to enforce the shape and contents of a string value. If the customer gives you an e-mail address and the regular expression doesn’t think the string looks like an e-mail address, the customer will see the error in Figure.
To someone who isn’t a developer (and even to some developers, too), the error message looks like someone sprinkled catnip on a keyboard before letting a litter of Norwegian Forest Cats run wild. You see how to make a friendlier error message in the next section.

Tagged . Bookmark the permalink.

Leave a Reply