In this article, I am going to discuss the Regular Expression Attribute in ASP.NET MVC application with examples. Please read our previous article where we discussed Required and StringLength Attribute in ASP.NET MVC application. At the end of this article, you will understand what are Regular Expression Attribute and how and when to use Regular Expression Attribute in ASP.NET MVC application with examples.
What is Regular Expression Attribute in ASP.NET MVC?
The Regular Expression Attribute is generally used for pattern matching validations in ASP.NET MVC applications.
Lets understand the Regular expression attribute with an example.
Suppose, we need to validate the Email ID of an employee, then we can achieve this very easily in the ASP.NET MVC application by using Regular expression attributes as shown below:
In the above example, we are applying both Required and RegularExpression attributes to the EmailID model property which ensures that the Email Id is a required field and along with it will validate the email id field value as shown below. When a user tries to enter an invalid Email ID and submit the page, then he will get the validation error message as shown below:
Another Example:
Here is the requirement for validating Name property
- UserName can contain the first and last names with a single space.
- The last name is optional. If the last name is not present, then there shouldnt be any space after the first name.
- Only upper and lower case alphabets are allowed.
This requirement can achieve very easily in ASP.NET MVC using RegularExpressionAttribute. In the Employee.cs class file, decorate the UserName property with the RegularExpression attribute as shown below.
Notice that, we are passing regular expression string to the attribute constructor. The Regular Expression Attribute is great for pattern matching and ensures that the value for the UserName property is in the format that we want. Also, notice that we are using a verbatim literal (@ symbol) string, as we dont want escape sequences to be processed.
Run the application and see the UserName field is work as expected. Understanding and writing regular expressions is beyond the scope of this Video. If you are interested in learning to write regular expressions, here is a link from MSDN
http://msdn.microsoft.com/en-us/library/az24scfc.aspx
The following website is very helpful, for writing and testing regular expressions. This website also contains commonly used regular expressions. In fact, I have picked up the regular expression for validating the UserName property from here.