Xpode.com        Click here to Print this article.

ASP.NET MVC interview questions: - What is data annotation validation in MVC? How to enable data annotation validation?

If you want to check string length, you can use “StringLength”.


public string FirstName { get; set; }

In case you want to use regular expression, you can use “RegularExpression” attribute.


public string Email { get; set; }

If you want to check whether the numbers are in range, you can use the “Range” attribute.


public int Age { get; set; }

Some time you would like to compare value of one field with other field, we can use the “Compare” attribute.

public string Password { get; set; }


public string ConfirmPass { get; set; }

In case you want to get a particular error message , you can use the “Errors” collection.

var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;

If you have created the model object yourself you can explicitly call “TryUpdateModel” in your controller to check if the object is valid or not.


In case you want add errors in the controller you can use “AddModelError” function.

ModelState.AddModelError("FirstName", "This is my server-side error.");

Enable data annotation validation on client side : -

It’s a two-step process first reference the necessary jquery files.

<script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>

<script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript"></script>

<script src="<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.js") %>" type="text/javascript"></script>

Second step is to call “EnableClientValidation” method.

<% Html.EnableClientValidation(); %>

Also see the following ASP.NET MVC interview questions video on creating a simple customer model/class: -


Contributed by:
Shivprasad koirala Koirala
I am a Microsoft MVP for ASP/ASP.NET and currently a CEO of a small E-learning company in India. We are very much active in making training videos , writing books and corporate trainings. Do visit my site http://www.questpond.com for .NET, C# , design pattern , WCF , Silverlight , LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server training and Interview questions and answers

Resourse address on xpode.com

Click here to go on website