Published: 28 May 2010
By: Brian Mains

An overview of validation in ASP.NET MVC 2.0.

Contents [hide]

The ASP.NET MVC 2 Series

  • Introduction to ASP.NET MVC 2.0 In this article, we'll begin examining the new features of ASP.NET MVC 2.0 by comparing what ASP.NET MVC offers against its predecessor, ASP.NET web forms.
  • ASP.NET MVC 2.0 User Interfaces The next part to this article series on MVC 2.0 is the user interface. We saw in the last article some basics on the changes of the user interface, which we'll delve into more in this article series. Here we will begin to look at how developers can construct the view user interface.
  • ASP.NET MVC 2.0 Using Multiple Actions Brian Mains explains how to use multiple actions in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Templating Templating is now in the ASP.NET MVC 2.0 framework, for .NET framework 3.5 and 4.0. We are going to take a look at these features.
  • ASP.NET MVC 2.0 Attributes An overview of ASP.NET MVC 2.0 Attributes.
  • ASP.NET MVC 2.0 Validation An overview of validation in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Areas A look at ASP.NET MVC 2.0 Areas.
  • ASP.NET MVC 2.0 and AJAX Part 1 ASP.NET MVC makes working with AJAX really easy; it's quite impressive how powerful the framework can be. JQuery adds extra features and makes AJAX calls really easy; we'll see that all here soon.
  • ASP.NET MVC 2.0 and AJAX Part 2 In this article, we are going to look at how you can utilize AJAX in your views, and utilize a concept called unobtrusive JavaScript to take advantage of a variety of situations. ASP.NET MVC provides AJAX features very easily as we previously saw, but this comes with a caveat, and it has mostly to do with the planning of the implementation. We’re going to examine these concerns in this article.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 1 In this article, we'll examine using the ADO.NET Entity Framework (ADO.NET EF). The 4.0 version has received some major upgrades, with some major API enhancements and fixes for most of the pain points within the designer.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 2 Out of the .NET framework 4.0 comes many great enhancements, the ADO.NET entity framework (ADO.NET EF) is among the top. The framework has improved upon some of the previous bugs (in version 1), as well as enhanced the API, including many new LINQ-to-SQL-like improvements. We're going to examine using these API features to create a generic version of of a data repository.
  • Complexity in ASP.NET MVC, Part 1: Dealing With Large Models At times, every developer has a web forms page or MVC view that ends up getting pretty complex, for various reasons. Whether it pulls in and integrates a lot of data (such as a portal page) or allows users to edit a lot of information, applications require data, and the amount of data grows over time. It’s a simple reality. We’re going to examine what a larger ASP.NET MVC view looks like, and some actions we can take to keep the model instantiation code as slim as possible.
  • Complexity in ASP.NET MVC, Part 2: Plan your AJAX Carefully Brian Mains discusses management of Ajax requests in ASP.NET MVC.
  • Using DI Containers in ASP.NET MVC How to use Dependency Injection containers in ASP.NET MVC.
  • Using Microsoft Unity in ASP.NET MVC Brian Mains continues his asp.net series with the unity application block.
  • Introduction

    The web forms model of development provides a pretty common way to validate data: by specifying the set of validation rules we wanted to apply the UI through an explicit validator control. A page would contain some input control (a text box), with a set of validators controls defined linked to it. Since more than one can be used (RequiredFieldValidator for required fields, RegularExpressionValidator for specialty data like phone number or email address, etc.), each validation ran independently of the other.

    If you have another client UI involved, such as a windows forms project, UI validation requires a duplication effort as a windows UI knows nothing of Asp.NET validation. This was a common reason for placing the validation rules in the business layer level, but for ease of use and efficiency in ASP.NET, the validation is specified also in the web page (typically because client-side validation prevents unneeded round trips to the server).

    It may seem that MVC works similarly, but the ASP.NET MVC framework attempts to bridge this gap between client-side and server-side validation and rules supplied in the business layer. In MVC 2.0, validation rules are applied in the model that's passed to the view, meaning the class passed as the model contains the validation rules directly. The typical way this can be done is through data annotations, the default approach to defining the rules of the client.

    Server-Side Validation

    A sample class that uses data annotations appears in Listing 1. Data annotations are attributes defined at the property level as metadata.

    Listing 1: Sample Class with Data Annotations

    Each property has one or more attributes associated with it (you can consider an attribute as being equivalent to a validation control in web forms). Any number of rules can be applied, but you have to be careful with applying too many rules, as rules may eventually counteract each other.

    The logic for the rule rests in the definition of the attribute. For instance, the RequiredAttribute class overrides the IsValid method it inherits from its base type, ValidationAttribute, and looks for a null value in the underlying data. This means that you can easily create your own custom attributes, but that is currently out of scope of this article.

    Once attributes are applied to a model, and this model is passed to a view, validation becomes very easy. We simply need the use of a ValidationMessageFor method to define the property in the model to suck in the validation rules for, and the placeholder to put the error message if the validation fails. Below is a sample form with validation.

    Listing 2: Setting up the sample form

    This example makes use of the new For syntax, using a lambda expression to identify the fields in the model to do something with (I discussed this in a previous article). The two expressions pointing to the Name and SKU properties specify the control and the validation information for the respective property in the model.

    The entire process looks like this: the user clicks the submit button to post the form data back to the server. The form posts back to an action method like in Listing 3.

    Listing 3: Our Action Method

    Note how I do not have to do any explicit validation "if property is null add error" statements; since the action method accepts a Product object, the model binder attempts to bind the Name and SKU MVC controls to the Name and SKU properties in the model. The data annotation validation rules (or other associated validation metadata) are extracted from the model's properties and the data is passed to each attribute's IsValid method. Any errors from the inputted data do two things: the field within the model is null (or the associated data type's default value), and the error is added to the model state. If everything checks out, a redirection happens.

    Client-Side Validation

    The ASP.NET MVC framework also utilizes client-side validation of forms. This client-side validation happens out of the box, all tucked into a nice little package called the MicrosoftMvcValidation script file. This script contains client-side framework components that complement their equivalent server-side attributes. Adding this script is core to setting up the validation framework.

    Below is a sample form for the client-side validation. Note the similarities to Listing 2.

    Listing 4: Setting up the sample form with AJAX

    This form is essentially the same except for the EnableClientValidation() method call. This method performs some preparation work to ensure that certain conditions in the application happen correctly. For instance, one of the first tasks that it does is to ensure that each <form> element on the page has a unique ID. This is necessary for the client-side framework to operate. It also establishes the FormContext class, a class that internally assists with the client validation features.

    Once all of this is established, a process on the client-side must also take place; the MicrosoftMvcValidation.debug.js script file sets up a lot of the core components to the validation framework. Some of these components are in the list below. Note that all of these components reside in the client-side Sys.Mvc framework.

    Validators – Validators like NumberValidator, RequiredValidator, RegularExpressionValidator, RangeValidator, etc. are defined in this script. These validators check for validity of input data through JavaScript, and mimic their server-side companion attribute.

    FormContext and FieldContext – These context objects assist with client-side validation. The FormContext manages each form and its validation summary, while the FieldContext manages each field being validated and the associated error messages that may appear.

    ValidatorRegistry – This component is the client-side registry of validators; each of the validators listed above is registered with this component, as well as any client-side components you've may write yourself.

    Each of these client-side components has a key role in the validation process.

    Conclusion

    Validation is very easy to setup in ASP.NET MVC. Since validation rules come from the Model, a change in 2.0, the rules to validate with can be applied all in one place. The model class defines attributes which the MVC framework can extract using reflection, and make these validations happen on both the server-side and client-side with relative ease.

    The ASP.NET MVC 2 Series

  • Introduction to ASP.NET MVC 2.0 In this article, we'll begin examining the new features of ASP.NET MVC 2.0 by comparing what ASP.NET MVC offers against its predecessor, ASP.NET web forms.
  • ASP.NET MVC 2.0 User Interfaces The next part to this article series on MVC 2.0 is the user interface. We saw in the last article some basics on the changes of the user interface, which we'll delve into more in this article series. Here we will begin to look at how developers can construct the view user interface.
  • ASP.NET MVC 2.0 Using Multiple Actions Brian Mains explains how to use multiple actions in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Templating Templating is now in the ASP.NET MVC 2.0 framework, for .NET framework 3.5 and 4.0. We are going to take a look at these features.
  • ASP.NET MVC 2.0 Attributes An overview of ASP.NET MVC 2.0 Attributes.
  • ASP.NET MVC 2.0 Validation An overview of validation in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Areas A look at ASP.NET MVC 2.0 Areas.
  • ASP.NET MVC 2.0 and AJAX Part 1 ASP.NET MVC makes working with AJAX really easy; it's quite impressive how powerful the framework can be. JQuery adds extra features and makes AJAX calls really easy; we'll see that all here soon.
  • ASP.NET MVC 2.0 and AJAX Part 2 In this article, we are going to look at how you can utilize AJAX in your views, and utilize a concept called unobtrusive JavaScript to take advantage of a variety of situations. ASP.NET MVC provides AJAX features very easily as we previously saw, but this comes with a caveat, and it has mostly to do with the planning of the implementation. We’re going to examine these concerns in this article.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 1 In this article, we'll examine using the ADO.NET Entity Framework (ADO.NET EF). The 4.0 version has received some major upgrades, with some major API enhancements and fixes for most of the pain points within the designer.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 2 Out of the .NET framework 4.0 comes many great enhancements, the ADO.NET entity framework (ADO.NET EF) is among the top. The framework has improved upon some of the previous bugs (in version 1), as well as enhanced the API, including many new LINQ-to-SQL-like improvements. We're going to examine using these API features to create a generic version of of a data repository.
  • Complexity in ASP.NET MVC, Part 1: Dealing With Large Models At times, every developer has a web forms page or MVC view that ends up getting pretty complex, for various reasons. Whether it pulls in and integrates a lot of data (such as a portal page) or allows users to edit a lot of information, applications require data, and the amount of data grows over time. It’s a simple reality. We’re going to examine what a larger ASP.NET MVC view looks like, and some actions we can take to keep the model instantiation code as slim as possible.
  • Complexity in ASP.NET MVC, Part 2: Plan your AJAX Carefully Brian Mains discusses management of Ajax requests in ASP.NET MVC.
  • Using DI Containers in ASP.NET MVC How to use Dependency Injection containers in ASP.NET MVC.
  • Using Microsoft Unity in ASP.NET MVC Brian Mains continues his asp.net series with the unity application block.
  • <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Brian Mains

    Brian Mains is an application developer consultant with Computer Aid Inc. He formerly worked with the Department of Public Welfare. In both places of business, he developed both windows and web applications, small and large, using the latest .NET technologies. In addition, he had spent many hou...

    This author has published 73 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category


    Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View
    A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Contr...
    jQuery Mobile ListView
    In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
    Exception Handling and .Net (A practical approach)
    Error Handling has always been crucial for an application in a number of ways. It may affect the exe...
    JQuery Mobile Widgets Overview
    An overview of widgets in jQuery Mobile.
    Book Review: SignalR: Real-time Application Development
    A book review of SignalR by Simone.

    You might also be interested in the following related blog posts


    Learning MVC - Part 5 Repository Pattern in MVC3 Application with Entity Framework read more
    A Beginner's Tutorial for Understanding and Implementing Custom Validations in ASP.NET MVC using DataAnnotations read more
    ASP.NET MVC 4 Client Side Validation read more
    ASP.NET MVC Client Side Validation read more
    ASP.NET MVC Server-Side Validation read more
    Implementing Remote Validation in MVC read more
    Learning MVC - Part 5 Repository Pattern in MVC3 Application with Entity Framework read more
    Learning MVC Part 6: Generic Repository Pattern in MVC3 Application with Entity Framework read more
    Building Client (JavaScript) Custom Validation in ASP.NET MVC 4 using jQuery read more
    Understanding the MvcRouteHandler and MvcHandler in ASP.NET MVC read more
    Top
     
     
     

    Please login to rate or to leave a comment.