In this article we will try to understand how we can use data annotations for doing validations in MVC web application.
This is the 11th MVC (Model view controller) tutorial and in this article we will try to understand how we can use data annotations for doing validations in MVC web application.
Alternatively if you are completely new to MVC, you can also see the videos to come up to speed.
Introduction
Validating data is one of the key things in any web application. As a developer you would like to run validation both on the client side (browser) and also on the server side.
So you would probably like to write the validation once and then expect the validation framework to generate the validation logic on both the ends.
Good news, this is possible by using data annotations.
In MVC you validate model values. So once the data comes inside the model you would like to question the model saying, is the data provided proper?, are values in range ? etc.
Data annotations are nothing but the metadata which you can apply on the model and the MVC framework will validate using the metadata provided.
In this lab let’s enforce validation by using data annotation. So the first things are use Lab 4 and create a simple model and a strong typed data entry view. In case you have come to this lab straight forward, please once have a look at ASP.NET MVC creation of data entry screen tutorial before proceeding ahead.
So assuming you have created the model and the strong typed view, let’s start applying data annotations.
Note: - The view created should be a strong typed view.
Step 1:- Decorate model with data annotation
Import the data annotation namespace as shown in the code snippet below.
using System.ComponentModel.DataAnnotations;
Let say we have a customer model and we want to ensure that the customer code field is compulsory.
So you can apply attribute “Required” as shown in the below code snippet. If the validation fails and you would like to display some error message, you can pass the “ErrorMessage” also.
public class Customer
{
[Required(ErrorMessage="Customer code is required")]
public string CustomerCode
{
set;
get;
}
}
Step 2:- Change the ASPX code
Now there are some code changes we would be doing in the ASPX code as compared to our previous lab. Inside the body we would like to display error message if the data is not proper. This is done by using the below code snippet.
<%= Html.ValidationSummary() %>
We also need to code our HTML form to input data. Below is the code snippet for the same. Please note the “EditorForModel” function will automatically generate UI controls looking at the model properties. So we do not need to create control individually as we did for Lab 4.
<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
{ %>
<%= Html.EditorForModel() %>
<input type="submit" value="Submit customer data" />
<%}%>
Step 3:- Enable Client validation
As said previously we would like to fire validation on both server and client side. In order to fire validations on the client side, we need to refer three JavaScript files as shown in the below code snippet.
<head runat="server">
<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>" type="text/javascript"></script>
<% Html.EnableClientValidation(); %>
</head>
Also note the call to “EnableClientValidation” method due to which client side validations are enabled.
<% Html.EnableClientValidation(); %>
Step 4:- Write your controller logic
From the UI when the form calls a post on the controller, you would like to know if the model state is proper or not. This can be done by checking the “ModelState.IsValid” property. So if this property is valid then call the save method and call the thanks view or else go back to the customer view.
[HttpPost]
public ActionResult PostCustomer(Customer obj)
{
if (ModelState.IsValid)
{
obj.Save();
return View("Thanks");
}
else
{
return View("Customer");
}
}
Step 5:- Run your application to see the action
Finally run your application and see the data annotation in action.
Summary of other data annotation attributes
There are other data annotation attributes which makes complex validation a breeze. Below are list of some of them:-
If you want to check string length, you can use “StringLength”.
[StringLength(160)]
public string FirstName { get; set; }
In case you want to use regular expression, you can use “RegularExpression” attribute.
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
public string Email { get; set; }
If you want to check whether the numbers are in range, you can use the “Range” attribute.
[Range(10,25)]
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; }
[Compare("Password")]
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.
TryUpdateModel(NewCustomer);
By profession I am a trainer if you are interested in c# training, you can visit me at c# and .NET training.