You are on page 1of 21

Hands-On Lab

ASP.NET MVC Custom Validation
Lab version: Last updated: 1.1.0 4/27/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......................................... 11 Task 4 Modifying the Create View to Execute Client-Side Validation ............................................ 12 Task 5 Running the Application ................................................................................................... 12
EXERCISE 3: USING IVALIDATABLEOBJECT CUSTOM VALIDATION.............................................. 13

Task 1 Implementing IValidatableObject Validation Method........................................................ 13 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 ...................................................................... 17 Task 3 Adding Unobtrusive jQuery to Master Page ...................................................................... 18 Task 4 Running the Application Using Unobtrusive jQuery Validation .......................................... 18
SUMMARY ............................................................................................................................................ 21

Page 2

Lastly. you will learn how to: y y y y 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 and ASP. The existing create and edit views in the StoreManager controller will process the new custom validation from the server side.NET MVC validation. Then. we recommend you to go over ASP.NET MVC validationbefore.NET MVC 3 Unobtrusive jQuery integration.NET IValidatableObjectto extend validation scope Integrate UnobtrusivejQuery library to enhanceclient side validation System Requirements You must have the following items to complete this lab: y y y ASP. If you have not used ASP. In the second exercise. you have been validating data from the create and edit album forms.NET4 IValidatableObject Interface. In ASP.NET MVC Helpers. Forms and Validation Hands-on Lab. you will use ASP. you will add JavaScript code and associate it to the previous custom validation. 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. executing the validation defined in the first exercise at client side with jQuery libraries. Forms and ValidationHand-on Lab. performing an extra validation at server side that will run after attribute validation is performed. you will implement a custom server-side validation using ASP. making the same views run that validation code at client side.Overview Note: This Hands-on Lab assumes you have basic knowledge of ASP. In order to achieve that.NET MVC and ASP.NET MVC Helpers. Objectives In this Hands-On Lab. in the first exercise you will create a custom validation property attribute and then add it to the Album model.NET MVC 3 Visual Studio 2010 Express SQL Server Database (Express edition or above) Page 3 .

Exercises This Hands-On Lab is comprised by the following exercises: 1. Exercise 1: Adding custom range validation 2. Exercise 3: Using IValidatableObject custom validation 4. Exercise 4: Using Unobtrusive jQuery at client side Estimated time to complete this lab: 45 minutes.\Source\Assets\CodeSnippets.microsoft. Next Step Exercise 1: Adding Custom Range Validation Using Validation Attributes Exercise 1: Adding Custom Range Validation Using Validation Attributes Page 4 . You can use this solution as a guide if you need additional help working through the exercises. Exercise 2: Adding validation at client side 3. Note:Each exercise is accompanied by an End folder containing the resulting solution you should obtain after completing the exercises. much of the code you will be managing along this lab is available as Visual Studio code snippets. To install the code snippets run . Setup Installing Code Snippets For convenience.vsi file.Note: You can install the previous system requirements by using the Web Platform Installer 3.com/fwlink/?LinkID=194638.0: http://go.

[AttributeUsage(AttributeTargets. System.All. System.sln at Source\Ex01-Server Side Custom Validation\Begin 2.Field | AttributeTargets. 5. 1. which will include all the custom rules.DataAnnotationsnamespace: C# using using using using System. Task 1 Adding a validation attributeclass In this task.ComponentModel.Collections. System. For that purpose.cs 4. Inherited = true)] publicclassPriceValidationAttribute : ValidationAttribute { } Note:AttributeUsage determines how custom attribute class s attributes can be applied. Add a new C# class into the Validations folder and rename it toPriceValidationAttribute.ComponentModel.AttributeTargets. Each attribute to be validated should have a new class inherited from ValidationAttribute. Open the begin solution MvcMusicStore. you will learn how to create a custom validation by using MVC3 ValidationAttribute class at server side.In this exercise. Additionally.cs and add a reference to the System. System. AllowMultiple = false.Property. System.DataAnnotations. which in this case can be set to fields and properties: C# using using using using System. System. [System. AllowMultiple = false.Generic. Open PriceValidationAttribute.Generic.Collections.Inherited = true)] Page 5 .ComponentModel. you have to add the AttributeUsageattribute specification.Web.DataAnnotations. Inherit the PriceValidationAttribute class fromValidationAttribute. 3. Create a new folder Validations at project root. you will include a range validation in the Store Manager example to validate that the price of an album belongs to a certain range.Web.AttributeUsage(System. you willadd a validation attribute class at server side.

then the attribute can be applied more than once in the target Inherit: If it is set to false. 7. then the attribute is not inherited by derived attribute classes.Generic. This step is required for custom validation at server side: Page 6 . Implementa class initializer and the methodIsValid from the base class.Linq. privatedecimal maxPrice = 100.Property.Collections. Property.Web. add the following code to the generated class: (Code Snippet ASP.ComponentModel.Field | AttributeTargets. To do this. You could read more about AttributeUsage in msdn.AttributeTargets. Define the thresholds for the album price range. Method or Field). usingSystem.01M. } } Note:The values ofminPriceand maxPriceare initialized here. namespaceMvcMusicStore. Inherited = true)] publicclassPriceValidationAttribute : ValidationAttribute { privatedecimal minPrice = 0. It is possible to use System.DataAnnotations.AttributeTargets:This parameter specifies all the application elements on which it is valid to apply an attribute.Validations { [AttributeUsage(AttributeTargets. or to specify each member (for example. Class.00M.NET MVC 3 Custom Validation Ex1 Custom Range Validation Thresholds CSharp) C# using System. AllowMultiple = false.All. 6. usingSystem. usingSystem. usingSystem. but they could be retrieved from a database query or a Web Service call. AllowMultiple: If it is set to true. making the application more maintainable.

100. using System. Replace current data annotation with the PriceValidation attribute: C# [Range(0.00")] [PriceValidation] Page 7 .minPrice || price >this.NET MVC 3 Custom Validation Ex1 Custom Range Validation IsValidCSharp) C# using System. ErrorMessage = "Price must be between 0.00.Collections.(Code Snippet ASP.Web. you will add a new data annotation tag to theAlbumclassthatwill be automatically linkedto the validation method just created: 1.cs file at MvcMusicStore\Models.Validations. 2.01M. Add Validations namespace into theAlbum class C# using MvcMusicStore.00M. public PriceValidationAttribute(): base("The price is not in a valid range") { } publicoverridebool IsValid(object value) { decimal price = (decimal)value. privatedecimal maxPrice = 100. } } Task 2 Creating the Custom Data Annotation In this task. if (price <this.Property. using System. using System.maxPrice) returnfalse. Open the Album.01.Linq. usingSystem.ComponentModel. returntrue.Generic. [AttributeUsage(AttributeTargets.Field | AttributeTargets.01 and 100. AllowMultiple = false.DataAnnotations. 3. Inherited = true)] publicclassPriceValidationAttribute : ValidationAttribute { privatedecimal minPrice = 0.

. 2. Browse/StoreManager/Create and click Savewithout filling the formto verify that you get the price range validation message: Page 8 . The project starts in the Home page. [Required(ErrorMessage = "Price is required")] [PriceValidation] publicobject Price { get. 1.After the replacement.Models { [MetadataType(typeof(AlbumMetaData))] publicpartialclassAlbum { // Validation rules for the Album class . set.. theAlbum. } } } Task 3 Running the Application In this task. Press F5 to run the Application.csfile should look like the following: C# namespace MvcMusicStore. you will test that the StoreManagerCreate View template validates the price using custom validation.

cs. as the error message will appear before saving the album.Linq. and rename it ModelClientPriceRangeValidationRule.Web.Mvcnamespace: C# using System.Mvc.Web.sln at Source\Ex02-Client Side Custom Validation\Begin.you will learn how to add validation at client side. usingSystem. Task 1 Creating a ModelClientValidationRule for price ranges Note:ModelClientValidationRule is an ASP. This derived class will provide a custom validation rule. In order to achieve that. Open the begin solution MvcMusicStore. For that purpose you will implement MVC3 IClientValidatable Interface at client side. you will create a new ModelClientValidationRule called ModelClientPriceRangeValidationRule. and add a reference to the System. Open ModelClientPriceRangeValidationRule. 3. usingSystem. 2.Web. any generic rule should inherit from this class. 1.NET MVC class that provides a base class container for client validation rules sent to the browser. usingSystem. Page 9 . This will improve the user experience. In this task. Create a new C# class file into Validations folder. In this exercise.cs.Collections.Generic.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. usingSystem.

minPrice).Validations { publicclassModelClientPriceRangeValidationRule : ModelClientValidationRule { publicModelClientPriceRangeValidationRule(stringerrorMessage. ValidationParameters. Page 10 .Mvc. namespaceMvcMusicStore.Validations { publicclassModelClientPriceRangeValidationRule: ModelClientValidationRule { } } 5. ValidationType = "priceOnRange". decimalmaxPrice) { ErrorMessage = errorMessage.NET MVC 3 Adding validation at client side Ex2 Constructor . Create a new class constructor forModelClientPriceRangeValidationRuleto set the base class properties with your custom parameters: (Code Snippet ASP. decimalminPrice.Add("minPrice". namespaceMvcMusicStore.CSharp) C# usingSystem.Linq. usingSystem. usingSystem.Web.Web.Mvc. Inherit the ModelClientPriceRangeValidationRuleclassfrom ModelClientValidationRule: C# using System.Web.Collections. usingSystem. ValidationParameters.Generic. usingSystem.4. } } } Note: In the following steps you will see how this piece is connected with the general solution. maxPrice).Add("maxPrice".

.. 1. IClientValidatable { . Task 3 Adding aJavaScript Function to Perform Client-SideValidation 1.ValidatorRegistry.Task 2 Adding attribute validation at client side In this task.. } .IClientValidatable 2..minPrice.. } // Client-Sidevalidation publicIEnumerable<ModelClientValidationRule>GetClientValidationRules(ModelMeta datametadata. You will note that it has the same logic as the IsValidmethod of PriceValidationAttributeclass created in the previous exercise: JavaScript Sys.".maxPrice). Open PriceValidationAttribute. publicclassPriceValidationAttribute : ValidationAttribute.js and insert the following client side code that will validate the price range. Page 11 . 2.ValidationParameters. Create a new JavaScript file at \MvcMusicStore\Scripts and rename it to PriceValidation. publicoverrideboolIsValid(object value) { . you will add a method toPriceValidationAttributeclass to perform validation at client-side. Open PriceValidation..js. this..minPrice.validators["priceOnRange"] = function(rule) { varminPrice = rule.csfrom\MvcMusicStore\Validations.CSharp) C# . this. yieldreturn rule. Make the PriceValidationAttribute class implement the IClientValidatable interface C# publicclassPriceValidationAttribute: ValidationAttribute. ControllerContextcontext) { var rule = newModelClientPriceRangeValidationRule("The price is not in a valid range.NET MVC 3 Adding validation at client side Ex2 GetClientValidationRules override ..Mvc. Make the PriceValidationAttributeoverride the method GetClientValidationRules (Code Snippet ASP.

The project starts in the Home page. 100]. Add references to the following three JavaScript files that will take care of Ajax features. Press F5 to run the Application.js"type="text/javascript"></script > <scriptsrc="/Scripts/PriceValidation. 2. var message = rule. You will see the following error message: Page 12 . you will test that the StoreManagercreateview template performs a range validation at client side when the user enters an album price. Open Create.js"type="text/javascript"></script> <%Html. %> <%using (Html. return function (value. }. Browse/StoreManager/Createand in the Price field enter a valueoutside of the validation range [0.BeginForm()) {%> Task 5 Running the Application In this task.01.ValidationParameters. 2.ErrorMessage. enable HTML client validation: HTML <h2>Create</h2> <scriptsrc="/Scripts/MicrosoftAjax. Task 4 Modifyingthe Create View to Execute Client-Side Validation 1.maxPrice.varmaxPrice = rule. } return true.aspx view from \Views\StoreManager.EnableClientValidation().js"type="text/javascript"></script> <scriptsrc="/Scripts/MicrosoftMvcValidation. context) { if (value >maxPrice || value <minPrice) { return false. MVC validation and the custom price validation. 1. Next. }.

performing an extra validation at server side that will run after attribute validation is performed. Now you will use IValidatableObject to prevent the insertion of repeated albums.NET4 IValidatableObject Interface. you will learn how to implement a custom server-side validation using ASP. Task 1 Implementing IValidatableObjectValidation Method Page 13 .Figure 2 Validating an album price at client side Next Step Exercise 3: Using IValidatableObject custom validation Exercise 3: Using IValidatableObject Custom Validation In this exercise.In the previous exercises you worked with validation attributes to perform custom validation of several attributes.

ToUpper() &&a.Title. Open the begin solution MvcMusicStore. if (storeDB. It has one member. newstring[] { "Title" }).Albums.csfile at \Models and implement IValidatableObject interface: C# namespaceMvcMusicStore. For that reason. The method will check if there is any album with the same title and artist in the database and returns a ValidationResult object. 2. which determines if the object that implements the interface is valid: IEnumerable<ValidationResult>Validate(ValidationContextvalidationContext) You could read more about ValidationContext in msdn. You will later note that the error message is displayed next to Title field. Open the Album.1.ComponentModel.DataAnnotation) provides a way to invalidate an object.ToUpper() == this.Title. 3.ArtistId)) yieldreturnnewValidationResult("Existing Album".Models { [MetadataType(typeof(AlbumMetaData))] publicpartialclassAlbum: IValidatableObject { Note: IValidatableObjectinterface (from System.Trim().Trim(). (Code Snippet ASP.sln at Source\Ex03-Custom Validation IValidatableObject\Begin.the use of partial classes to implement Validate method is recommended. Implement IValidatableObject Validate method on Album class. Page 14 . Validate Method.NET MVC 3 Adding IValidatableObject validation Ex3 Validate method CSharp) C# publicIEnumerable<ValidationResult>Validate(ValidationContextvalidationContext ) { MusicStoreEntitiesstoreDB = newMusicStoreEntities().Any(a =>a. As Validate method is implemented into Model classes. } Note: ValidationResulthas a message ( Existing album ) and a target field in which the error is associated ( Title ).ArtistId == (int)this. youmight not feel comfortable with the idea ofhaving logic inside the model.

Then. 1. Fill the form with the following data: Greatest Hits in the Titlefield and Lenny Kravitz for Artist. You will get the error messageExisting Albumat the right of the title: Figure 3 Validating the insertion of an existing album Next Step Exercise 4: Using Unobtrusive jQuery at client side Page 15 . The project starts in the Home page. 3. write any valid data in the other fields. Press Save to submit the form. 2. 4. Press F5 to run the Application. Browse /StoreManager/Create. you will try to create a repeated album to test the validation.Task 2 Running the Application In this task.

The project starts in the Home page. 2. Note: The Unobtrusive jQueryuses data-ajax prefix JavaScript to invoke action methods on the server rather than intrusively emitting inline client scripts.sln at Source\Ex04-Unobtrusive JavaScript Validation\Begin and press F5to run the application. you will run the application before including jQuery in order to compare both validation models.you will learn how to enable MVC 3 Unobtrusive jQuery validation at client side. Browse /StoreManager/Create and click Savewithout filling the form to verify that you get validation messages: Figure 4 Client validation disabled Page 16 . Open the begin solution MvcMusicStore. 1. Task 1 Running the Application before Enabling Unobtrusive jQuery In this task. For that reason you will include jQuery libraries into the Master Page and enable unobtrusive jQuery globally.Exercise 4: Using Unobtrusive jQuery at Client Side In this exercise.

config In this task.cs to get the same results: HtmlHelper.NET MVC 3 projects.Title"type="text"value=""/> <spanclass="field-validation-error">An Album Title is required</span> </p> <p> <labelfor="Album_Price">Price</label> <inputclass="input-validationerror"id="Album_Price"name="Album.config file. which is by default set to false in all new ASP. 1.00</span> Task 2 Enabling Client Validation fromWeb. open theCreateview source code: HTML Create.Config <configuration> <appSettings> <addkey="ClientValidationEnabled"value="true"/> <addkey="UnobtrusiveJavaScriptEnabled"value="true"/> </appSettings> Note: You can also enable client validation by code at Global. Page 17 . In the browser.Web.you will enable unobtrusive jQueryclient validation from Web. XML .asax.01 and 100.Config file at project root.Price"type="text"value="0"/> <spanclass="field-validation-error">Price must be between 0.html <formaction="/StoreManager/Create"method="post"> <divclass="validation-summary-errors"><ul><listyle="display:none"></li> </ul></div> <p> <labelfor="Album_Title">Title</label> <inputclass="input-validationerror"id="Album_Title"name="Album. Open Web.ClientValidationEnabled = true.3.and make sure that theClientValidationEnabled key value is set to true.

/Scripts/jquery.css"rel="Stylesheet"type="text/css"/> <title><asp:ContentPlaceHolderID="TitleContent"runat="server"/></title> <scriptsrc=". 2.validate.. Open Site.js"type="text/javascript"></ script> </head> Note:All these jQuery libraries are included in all MVC 3 new projects. you can assign ClientValidationEnabled attribute into any controller to have a custom behavior. Task 4 Running the ApplicationUsing Unobtrusive jQueryValidation In this task. you will test that the StoreManagercreate view template performs client side validation using jQuery libraries when the user creates a new album.you will add the unobtrusive jQuery references into the Master Page. Add MVC 3 script references to jQuery: XML <headrunat="server"> <linkhref="/Content/Site.js"type="text/javascript"></script> <scriptsrc=". 2./Scripts/jquery.. Task 3 Adding Unobtrusive jQuery to Master Page In this task. Press F5to run the application../. You can find more libraries in the project s folder /Scripts./.1.Master at Views\Shared. Browse /StoreManager/Create and click Savewithout filling the form to verify that you get validation messages: Page 18 .. The project starts in the Home page./Scripts/jquery-1..unobtrusive. 1.validate.Additionally.js"type="text/javascript"></script> <scriptsrc=". 1.4./..

unobtrusive./Scripts/jquery.1.Title"type="text"value=""/> </p> <p> <labelfor="Album_Price">Price</label> <inputdata-val="true"data-val-number="The field Price must be a number.4../Scripts/jquery-1.validate../..validate.Figure 5 Client validation with jQueryenabled 3..."dataval-range="Price must be between 0././. open the source code for Create view: HTML </title> <scriptsrc=". In the browser..01 and 100.js"type="text/javascript"></script> <scriptsrc="."data-val-length-max="160"data-val-required="An Album Title is required"id="Album_Title"name="Album./Scripts/jquery.00"data-val-range-max="100"data- Page 19 .js"type="text/javascript"></script> <scriptsrc=".js"type="text/javascript"></ script> </head> <p> <labelfor="Album_Title">Title</label> <inputdata-val="true"data-val-length="The field Title must be a string with a maximum length of 160.

Price"data-valmsgreplace="true"></span> </p> <spanclass="field-validation-valid"data-valmsg-for="Album. Price attribute has the following data annotation in the model: [Required(ErrorMessage = "Price is required")] [Range(0. set. Then." data-val-range="Price must be between 0. Unobtrusive jQuery adds an attribute with data-valrulename="message". ErrorMessage = "Price must be between 0.01 and 100.01. } After using UnobtrusivejQuery.01 and 100.01"data-val-required="Price is required"id="Album_Price"name="Album.00. 100.Price"type="text"value="0"/> <spanclass="field-validation-valid"data-valmsg-for="Album. Below is a list of tags that Unobtrusive jQuery inserts into the html input field to perform client validation: y y y y y y y Data-val Data-val-number Data-val-range Data-val-range-min / Data-val-range-max Data-val-required Data-val-length Data-val-length-max / Data-val-length-min All the data values are filled with model Data Annotation. all the logic that works at server side can be run at client side.00" Page 20 .val-range-min="0.Title"data-valmsgreplace="true"></span> </p> Note: For each client validation rule. the generated code is: <input data-val="true" data-val-number="The field Price must be a number.00")] public object Price { get. For example.

Price" type="text" value="0" /> Next Step Summary Summary By completing this Hands-On Lab you have learned how to use custom validations in your page with the user of the following concepts: y y y y y y Data annotations for model validation ASP.NET MVC 3 IClientValidatable interface A Custom MVC ModelClientValidationRule MVC ValidationAttribute inheritance A Custom server validation using IValidatableObject interface ASP.data-val-range-max="100" data-val-range-min="0.01" data-val-required="Price is required" id="Album_Price" name="Album.NET MVC 3 Unobtrusive jQuery validation Page 21 .