How to validate using Data annotation(MVC tutorial number 11)?

Questpond
Posted by in ASP.NET MVC category on for Intermediate level | Points: 250 | Views : 26094 red flag
Rating: 5 out of 5  
 2 vote(s)

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.

mvc

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.

Article description MVC ( Model view controller) videosMVC ( Model view controller) Article links
A simple Hello world ASP.NET MVC ( Model view controller) application. Hello word MVC Tutorial video http://www.dotnetfunda.com/articles/article1297-how-to-create-a-simple-hello-world-aspnet-mvc-tutorial-no-1-.aspx
In this video we will see how we can share data between controller and the view using view data. MVC Tutorial video 2 Viewdata http://www.dotnetfunda.com/articles/article1310-how-to-pass-data-from-controllers-to-views-in-aspnet-mvc-tutorial-no-2-.aspx
In this article we will create a simple customer model, flourish the same with some data and display the same in a view. MVC Tutorial video 3 Simple model and view example http://www.dotnetfunda.com/articles/article1317-how-to-create-a-simple-model-in-aspnet-mvc-and-display-the-same-tutorial-.aspx
In this article we will create a simple customer data entry screen with some validation on the view. MVC tutorial video 4 Simple customer data entry screen. http://www.dotnetfunda.com/articles/article1388-how-to-create-a-simple-aspnet-mvc-data-entry-screen-tutorial-no-4-.aspx
This article will demonstrate how to expedite your MVC development process using HTML helper classes.NA http://www.dotnetfunda.com/articles/article1415-how-to-create-mvc-model-view-controller-views-faster-by-using-html-helper-.aspx
This article demonstrates how we can do unit testing in MVC (Model view controller) applications.NA http://www.dotnetfunda.com/articles/article1429-how-can-we-do-unit-test-in-mvc-model-view-controller-application-tutoria-.aspx
This article demonstrates how we can define custom routing in MVC applications.NA http://www.dotnetfunda.com/articles/article1485-what-is-mvc-model-view-controller-routing-tutorial-number-7-.aspx
This article demonstrates how we can validate data passed in MVC URL’s.NA http://www.dotnetfunda.com/articles/article1527-how-to-validate-data-provided-in-mvc-urls-mvc-tutorial-number-8-.aspx
In this article we will see how to create outbound URL’s in MVC applications.NA http://www.dotnetfunda.com/articles/article1596-how-to-create-mvc-outbound-urls-mvc-tutorial-number-9.aspx
In this article we will see how to create reusable views using MVC partial views. http://www.dotnetfunda.com/articles/article1831-how-to-create-partial-views-mvc-tutorial-number-10.aspx
Page copy protected against web site content infringement by Copyscape

Login to vote for this post.

Comments or Responses

Posted by: Samarmir on: 4/20/2012 | Points: 25
thanks for a nice article, and thanks for the whole mvc series.
its nice to see that mvc is getting some attention at dotnetfunda.

Login to post response

Comment using Facebook(Author doesn't get notification)