Customizing Validation Attributes in MVC

2 comments

Note: Thank you for visiting my blog. However, this blog is not maintained actively anymore. This post is now also in my new blog. Feel free to leave a comment there.

Background

As many of you already know, MVC provides validation attribute functionality to validate view models. A few very commonly used validation attributes are: Required, RegularExpression and Range. Below is one simple example:


public class Person
    {
        [Required(ErrorMessage = "Please Enter your name")]
        public string Name { get; set; }
 
        [Required(ErrorMessage = "Please Enter your Email")]
        [RegularExpression(".+\\@.+\\‥+", ErrorMessage = "Please Enter valid Email")]
        public string Email { get; set; }
 
        [Required(ErrorMessage = "Please Enter your Phone")]
        public string Phone { get; set; }
    }


Which will give you the following output:
This default behavior is good for less complex application, where you can apply factory made validation without any considerable effort from your side.

You can also enable client side validation(validation will be done at client side without server post back) by adding/modifying the following lines in the
1. Web.config file:
<configuration>
  <appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
</configuration>

2. Layout / View page (of course you can use the latest version of jQuery):
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>


So far so good, Now lets complicate it

Lets assume that this application is going to be used by people from different regions and every region has a specific format for phone number. Every region has a separate set of special characters to be allowed for the phone number.