ASP.NET MVC 3: Using Annotations for Data Validation
Posted by: Mahesh Sabnis ,
on 11/3/2011,
in
Category ASP.NET MVC
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:
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:
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:
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:
Step 9: Create on the ‘Create’ button, the below result will be displayed:
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:
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.
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!
Was this article worth reading? Share it with fellow developers too. Thanks!
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