DOCX

introduction to ASPNET MVC Custom Validation in VS2010

By Derrick Hawkins,2014-09-19 17:37
12 views 0
introduction to ASPNET MVC Custom Validation in VS2010

Hands-On Lab

    ASP.NET MVC Custom Validation

Lab version: 1.1.0

    Last updated: 9/19/2011

    Page 1

CONTENTS

    OVERVIEW ............................................................................................................................................. 3

    EXERCISE 1: ADDING CUSTOM RANGE VALIDATION USING VALIDATION ATTRIBUTES .............. 4

    Task 1 Adding a validation attribute class ...................................................................................... 5

    Task 2 Creating the Custom Data Annotation ................................................................................ 7

    Task 3 Running the Application ..................................................................................................... 8

    EXERCISE 2: ADDING VALIDATION AT CLIENT SIDE ......................................................................... 9

    Task 1 Creating a ModelClientValidationRule for price ranges ....................................................... 9

    Task 2 Adding attribute validation at client side .......................................................................... 11

    Task 3 Adding a JavaScript Function to Perform Client-Side Validation ........................................ 12

    Task 4 Modifying the Create View to Execute Client-Side Validation ............................................ 12

    Task 5 Running the Application ................................................................................................... 13

    EXERCISE 3: USING IVALIDATABLEOBJECT CUSTOM VALIDATION ............................................. 14

    Task 1 Implementing IValidatableObject Validation Method ....................................................... 14

    Task 2 Running the Application ................................................................................................... 15

    EXERCISE 4: USING UNOBTRUSIVE JQUERY AT CLIENT SIDE ...................................................... 16

    Task 1 Running the Application before Enabling Unobtrusive jQuery ........................................... 16

    Task 2 Enabling Client Validation from Web.config ...................................................................... 18

    Task 3 Adding Unobtrusive jQuery to Master Page ...................................................................... 18

    Task 4 Running the Application Using Unobtrusive jQuery Validation .......................................... 19 SUMMARY ............................................................................................................................................ 21

    Page 2

Overview

    Note: This Hands-on Lab assumes you have basic knowledge of ASP.NET MVC and ASP.NET MVC

    validation. If you have not used ASP.NET MVC validation before, we recommend you to go over

    ASP.NET MVC Helpers, Forms and Validation Hand-on Lab.

In ASP.NET MVC Helpers, Forms and Validation Hands-on Lab, you have been validating data from the

    create and edit album forms. In this Hands-on Lab, you will use custom validation logic to control price range in the server side as well as in the client.

    In order to achieve that, in the first exercise you will create a custom validation property attribute and then add it to the Album model. The existing create and edit views in the StoreManager controller will process the new custom validation from the server side.

    In the second exercise, you will add JavaScript code and associate it to the previous custom validation, making the same views run that validation code at client side.

    Then, you will implement a custom server-side validation using ASP.NET4 IValidatableObject Interface, performing an extra validation at server side that will run after attribute validation is performed. Lastly, you will use ASP.NET MVC 3 Unobtrusive jQuery integration, executing the validation defined in the first exercise at client side with jQuery libraries.

    Objectives

    In this Hands-On Lab, you will learn how to:

    ; Create a custom validation attribute to extend the validation capabilities of the solution

    ; Run the validation logic at client side to improve user experience

    ; Implement ASP.NET IValidatableObject to extend validation scope

    ; Integrate Unobtrusive jQuery library to enhance client side validation

System Requirements

    You must have the following items to complete this lab:

    ; ASP.NET and ASP.NET MVC 3

    ; Visual Studio 2010 Express

    ; SQL Server Database (Express edition or above)

    Page 3

    Note: You can install the previous system requirements by using the Web Platform Installer

    3.0: http://go.microsoft.com/fwlink/?LinkID=194638.

Setup

    Installing Code Snippets

    For convenience, much of the code you will be managing along this lab is available as Visual Studio code snippets. To install the code snippets run .\Source\Assets\CodeSnippets.vsi file.

Exercises

    This Hands-On Lab is comprised by the following exercises:

    1. Exercise 1: Adding custom range validation

    2. Exercise 2: Adding validation at client side

    3. Exercise 3: Using IValidatableObject custom validation

    4. Exercise 4: Using Unobtrusive jQuery at client side

Estimated time to complete this lab: 45 minutes.

    Note: Each exercise is accompanied by an End folder containing the resulting solution you should

    obtain after completing the exercises. You can use this solution as a guide if you need additional help working through the exercises.

Next Step

    Exercise 1: Adding Custom Range Validation Using Validation Attributes

    Exercise 1: Adding Custom Range Validation Using Validation Attributes

    Page 4

In this exercise, you will learn how to create a custom validation by using MVC3 ValidationAttribute class

    at server side. For that purpose, you will include a range validation in the Store Manager example to

    validate that the price of an album belongs to a certain range. Task 1 Adding a validation attribute class

    In this task, you will add a validation attribute class at server side. Each attribute to be validated should

    have a new class inherited from ValidationAttribute.

    1. Open the begin solution MvcMusicStore.sln at Source\Ex01-Server Side Custom

    Validation\Begin

    2. Create a new folder Validations at project root, which will include all the custom rules.

    3. Add a new C# class into the Validations folder and rename it to PriceValidationAttribute.cs

    4. Open PriceValidationAttribute.cs and add a reference to the

    System.ComponentModel.DataAnnotations namespace:

    C#

    using System;

    using System.Collections.Generic;

    using System.Web;

    using System.ComponentModel.DataAnnotations;

    5. Inherit the PriceValidationAttribute class from ValidationAttribute. Additionally, you have to

    add the AttributeUsage attribute specification, which in this case can be set to fields and

    properties:

    C#

    using System;

    using System.Collections.Generic;

    using System.Web;

    using System.ComponentModel.DataAnnotations;

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property,

    AllowMultiple = false, Inherited = true)]

    public class PriceValidationAttribute : ValidationAttribute

    {

    }

    Note:AttributeUsage determines how custom attribute class’s attributes can be applied.

     [System.AttributeUsage(System.AttributeTargets.All,

     AllowMultiple = false, Inherited = true)]

    Page 5

AttributeTargets: This parameter specifies all the application elements on which it is valid to

    System.AttributeTargets.All, or to specify each apply an attribute. It is possible to use

    member (for example, Class, Property, Method or Field).

AllowMultiple: If it is set to true, then the attribute can be applied more than once in the

    target

Inherit: If it is set to false, then the attribute is not inherited by derived attribute classes.

You could read more about AttributeUsage in msdn.

    6. Define the thresholds for the album price range. To do this, add the following code to the

    generated class:

    (Code Snippet ASP.NET MVC 3 Custom Validation Ex1 Custom Range Validation Thresholds - CSharp)

    C#

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using System.ComponentModel.DataAnnotations;

namespace MvcMusicStore.Validations

    {

     [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property,

    AllowMultiple = false, Inherited = true)]

     public class PriceValidationAttribute : ValidationAttribute

     {

     private decimal minPrice = 0.01M;

     private decimal maxPrice = 100.00M;

     }

    }

    Note: The values of minPrice and maxPrice are initialized here, but they could be retrieved from a database query or a Web Service call, making the application more maintainable.

    7. Implement a class initializer and the method IsValid from the base class. This step is required for custom validation at server side:

    Page 6

(Code Snippet ASP.NET MVC 3 Custom Validation Ex1 Custom Range Validation IsValid-

    CSharp)

    C#

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using System.ComponentModel.DataAnnotations;

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]

    public class PriceValidationAttribute : ValidationAttribute {

     private decimal minPrice = 0.01M;

     private decimal maxPrice = 100.00M;

     public PriceValidationAttribute(): base("The price is not in a valid

    range")

     {

     }

     public override bool IsValid(object value)

     {

     decimal price = (decimal)value;

     if (price < this.minPrice || price > this.maxPrice)

     return false;

     return true;

     }

    }

    Task 2 Creating the Custom Data Annotation

    In this task, you will add a new data annotation tag to the Album class that will be automatically linked

    to the validation method just created:

    1. Open the Album.cs file at MvcMusicStore\Models.

    2. Add Validations namespace into the Album class

    C#

    using MvcMusicStore.Validations;

    3. Replace current data annotation with the PriceValidation attribute: C#

    [Range(0.01, 100.00, ErrorMessage = "Price must be between 0.01 and 100.00")]

    Page 7

    [PriceValidation]

    After the replacement, the Album.cs file should look like the following:

    C#

    namespace MvcMusicStore.Models

    {

     [MetadataType(typeof(AlbumMetaData))]

     public partial class Album

     {

     // Validation rules for the Album class

     ...

     [Required(ErrorMessage = "Price is required")]

     [PriceValidation]

     public object Price { get; set; }

     }

    }

    Task 3 Running the Application

    In this task, you will test that the StoreManager Create View template validates the price using custom

    validation.

    1. Press F5 to run the Application.

    2. The project starts in the Home page. Browse /StoreManager/Create and click Save without

    filling the form to verify that you get the price range validation message:

    Page 8

    Figure 1

    Validating an album price

Next Step

    Exercise 2: Adding validation at client side

    Exercise 2: Adding Validation at Client Side

    In the previous exercise you added a custom range validation method for the album price in the server side.

    In this exercise, you will learn how to add validation at client side. For that purpose you will implement MVC3 IClientValidatable Interface at client side. This will improve the user experience, as the error message will appear before saving the album.

    Task 1 Creating a ModelClientValidationRule for price ranges

    Page 9

Note: ModelClientValidationRule is an ASP.NET MVC class that provides a base class container for

    client validation rules sent to the browser. In order to achieve that, any generic rule should inherit

    from this class.

    In this task, you will create a new ModelClientValidationRule called

    ModelClientPriceRangeValidationRule. This derived class will provide a custom validation rule.

    1. Open the begin solution MvcMusicStore.sln at Source\Ex02- Client Side Custom

    Validation\Begin.

    2. Create a new C# class file into Validations folder, and rename it

    ModelClientPriceRangeValidationRule.cs.

    3. Open ModelClientPriceRangeValidationRule.cs. and add a reference to the System.Web.Mvc

    namespace:

    C#

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using System.Web.Mvc;

4. Inherit the ModelClientPriceRangeValidationRule class from ModelClientValidationRule:

    C#

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using System.Web.Mvc;

    namespace MvcMusicStore.Validations

    {

     public class ModelClientPriceRangeValidationRule:

    ModelClientValidationRule

     {

     }

    }

    5. Create a new class constructor for ModelClientPriceRangeValidationRule to set the base class

    properties with your custom parameters:

    (Code Snippet ASP.NET MVC 3 Adding validation at client side Ex2 Constructor - CSharp)

    Page 10

Report this document

For any questions or suggestions please email
cust-service@docsford.com