What you want to see on DotNetFunda.com ?
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 3069 |  Welcome, Guest!   Register  Login
Home > Articles > ASP.NET MVC > How to validate using Data annotation(MVC tutorial number 11)?

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

2 vote(s)
Rating: 5 out of 5
Article posted by Questpond on 4/19/2012 | Views: 9629 | Category: ASP.NET MVC | Level: Intermediate | Points: 250 red flag


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

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Experience:0 year(s)
Home page:http://www.questpond.com
Member since:Wednesday, September 03, 2008
Level:Starter
Status: [PanelMember] [Member] [Microsoft_MVP] [MVP] [Administrator]
Biography:

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 for 
.NET, C# , design pattern , WCF , Silverlight
, LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server  training 
and Interview questions and answers

 Responses
Posted by: Samarmir | Posted on: 20 Apr 2012 02:07:43 AM | 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.

>> Write Response - Respond to this post and get points
Related Posts

In this article we are going to know the software requirements to work with asp.net mvc4 and Supported Templates , Folder structure of an Asp.Net MVC4 application

In this article, we will try to understand how an MVC application structure looks like, the application components and its functionality with a static and a dynamic output example.

This is the 6th MVC (Model view controller) tutorial and in this article we will look in to how we can do unit testing using VSTS unit test suite.

Normally Jquery unobtrusive validation in MVC3 has some default style here we can look at a validation performed in Custom Style by modifying jquery.validate.unobtrusive.js file and applying some styles to it

In this article I am going to explain about Routing in ASP.NET MVC

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/24/2013 12:24:13 PM