ASP.NET MVC 3: Using Annotations for Data Validation

Posted by: Mahesh Sabnis , on 11/3/2011, in Category ASP.NET MVC
Views: 72036
Abstract: In this article, you will learn how to perform validation in an ASP.NET MVC application by using Data Annotation validators. Data Annotation validators enable you to perform validation using a declarative validation style, i.e. simply by adding one or more attributes.

Implementing Data Validations in a Web Application is a challenging task. Most of the time, a developer gets confused on whether to validate the user input on client side or server side. In Server side validations, the logic gets executed on the server. Although its secure, for every input validation, the web server logic is executed which makes validation a time consuming process and the end-user has to wait for the response (which is really irritating sometimes). Although Client-side validation is quicker and provides instant feedback, there’s always a fear of users turning off scripting and by passing that validation.

In ASP.NET Web Forms, developers are provided with validation controls which give instant feedback to the end-user. In case of ASP.NET MVC 3, our primary focus is on validating Model values. Since MVC framework is extensible, the validation logic can be built and customized to your requirements (like using a custom model metadata provider). You can also combine data annotations metadata with a custom policy. However the default style provided by the ASP.NET MVC framework is Data Annotations – i.e. a declaritive validation style using attributes and we will take an overview of the same in this article.

 

Note: Since MVC 2 was compiled against .NET 3.5, it did not have Data Annotations. Data Annotations is a .NET 4 feature.

In this article, I will focus on the use of Data-Annotations for validating our Model entity. After following the steps in this article, you can expect the following validations in place, as below:

Step 1: Open VS2010 and create an ASP.NET MVC 3 application, name it as ‘MVC3_DataValidation’. For simplicty sake, ignore the other folders in the project.

Step 2: Right-Click the Models folder and add a class file, name it as ‘ModelClasses.cs’. Add the following classes in it:

mvc-data-validation

The above code makes use of ‘System.ComponentModel.DataAnnotations’. The following attributes are used here:

  • Required: Specifies that the Data value is required.

  • StringLength: Specifies minimum and maximum length of characters allowed for the specified data field.

  • RegularExpression: The format of the data value to be entered in the specified field. The value entered for the data field must match with the regular expression.

  • Compare: This is present under the namespace ‘System.Web.Mvc’. This is used to compare to properties of the model.

Step 3: Right-Click the Controller folder and select Add > Controller, name it as ‘CustomerOrderController.cs’. In this controller, add methods e.g. Index(), Create() and Create() with HttpPost attribute. Write the following code in it:

asp-mvc-controller

Step 4: Right-Click on the Index() method and select ‘Add View’, select the Model class as ‘CustomerOrder’ and scaffold template as List. Make sure that the View Engine is ‘Razor’.

Step 5: Open ‘_Layout.cshtml’ and add the following code representing a link:

<li>@Html.ActionLink("CustomerOrder", "Index", "CustomerOrder")</li>

Step 6: Right-Click the Create() method i.e. the one which does not have HttpPost attribute and select ‘Add View’ > select model class as ‘CustomerOrder’ and scaffold template as ‘Create’.

Step 7: Run the application and the following result will be displayed:

image

Step 8: Click on ‘CustomerOrder’ and it will display an ‘Index’ view. Click on the ‘Create New’ link of the Index view and the following result will be displayed:

Validation using Data Annotations

Step 9: Create on the ‘Create’ button, the below result will be displayed:

Validation using Data Annotations

Enter a value e.g. ‘dsvads’in the Email filed and enter a non-matching value in te ConfirmEmail field. You should see the following:

Validation using Data Annotations

Conclusion: Using the Data-Annotations feature in MVC 3, it is now easy for web application developers to implement secure validation which provides instant feedback to the end-user.

The entire source code of this article can be downloaded over here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @maheshdotnet or connect with him on LinkedIn


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Sebastian on Friday, November 4, 2011 1:29 AM
I would have used a strongly-typed view so you could save you some Time on the Create Action.
Comment posted by Mahesh Sabnis on Monday, November 7, 2011 12:53 AM
Hi Sebastian,
  Yest its correct. I will take care of the same in my next articles.
Thanks
REgards
Mahesh Sabnis
Comment posted by friism on Sunday, February 19, 2012 11:42 PM
At AppHarbor, we've created a [PhoneNumber] attribute to validate phonenumbers: http://blog.appharbor.com/2012/02/03/net-phone-number-validation-with-google-libphonenumber
Comment posted by Richard on Thursday, May 31, 2012 10:13 AM
Can annotations be used to do validation between fields (other than "password" matches "retype_password") ?    

Example 1.  "From_Date" cannot be later than "To_Date"

or

Example2 "Provide at least 1 of Email address, Telephone no or postal address"
Comment posted by Mahesh Sabnis on Saturday, June 23, 2012 6:18 AM
Hi Richard,
  I am currently the similar requirements and will post in  short duration.
Thanks
Regards
Mahesh
Comment posted by EDU on Wednesday, May 28, 2014 12:13 AM
how about setting the default value on a metadata using data annotations?? is it possible.. can you give sample codes