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


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#Copy Code
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    

  4. Inherit the ModelClientPriceRangeValidationRule class from ModelClientValidationRule:
    C#Copy Code
    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)

    C#Copy Code
    using System.Web.Mvc;
    
    namespace MvcMusicStore.Validations
    {
        public class ModelClientPriceRangeValidationRule : ModelClientValidationRule
        {
            public ModelClientPriceRangeValidationRule(string errorMessage, decimal minPrice, decimal maxPrice)
            {
                ErrorMessage = errorMessage;
    
                ValidationType = "priceOnRange";
    
                ValidationParameters.Add("minPrice", minPrice);
                ValidationParameters.Add("maxPrice", maxPrice);
            }
        }
    }
    

    Note:
    In the following steps you will see how this piece is connected with the general solution.


Task 2: Adding attribute validation at client side

In this task you will add a method to PriceValidationAttribute class to perform validation at client-side.

  1. Open PriceValidationAttribute.cs from \MvcMusicStore\Validations
  2. Make the PriceValidationAttribute class implement the IClientValidatable interface
    C#Copy Code
        public class PriceValidationAttribute : ValidationAttribute, IClientValidatable
    

  3. Make the PriceValidationAttribute override the method GetClientValidationRules

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

    C#Copy Code
    ...
        public class PriceValidationAttribute : ValidationAttribute, IClientValidatable
        {
            ...
            public override bool IsValid(object value)
            {
                ...
            }
    
           // Client-Side validation
            public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
            {
                var rule = new ModelClientPriceRangeValidationRule("The price is not in a valid range.", this.minPrice, this.maxPrice);
    
                yield return rule;
            }
    ...
    

Task 3: Adding a JavaScript function to perform client-side validation

  1. Create a new JavaScript file at \MvcMusicStore\Scripts and rename it to PriceValidation.js
  2. Open PriceValidation.js and insert the following client side code that will validate the price range. You will note that it has the same logic as the IsValid method of PriceValidationAttribute class created in the previous exercise:
    JavaScriptCopy Code
    Sys.Mvc.ValidatorRegistry.validators["priceOnRange"] = function(rule) {
        var minPrice = rule.ValidationParameters.minPrice;
        var maxPrice = rule.ValidationParameters.maxPrice;
        var message = rule.ErrorMessage;
    
        return function (value, context) {
            if (value > maxPrice || value < minPrice) {
                return false;
            }
            return true;
        };
    };
    

Task 4: Modifying the create view to execute client-side validation

  1. Open Create.aspx view from \Views\StoreManager
  2. Add references to the following three JavaScript files that will take care of Ajax features, MVC validation and the custom price validation. Next, enable HTML client validation:
    HTMLCopy Code
    …
        <h2>Create</h2>
    
    <script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
        <script src="/Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
        <script src="/Scripts/PriceValidation.js" type="text/javascript"></script>
        <% Html.EnableClientValidation(); %>
        <% using (Html.BeginForm()) {%>
    …
    

Task 5: Running the Application

In this task you will test that the StoreManager create view template performs a range validation at client side when the user enters an album price.

  1. Press F5 to run the Application.
  2. The project starts in the Home page. Browse /StoreManager/Create and in the Price field enter a value outside of the validation range [0.01, 100]. You will see the following error message:

    Figure 2
    Validating an album price at client side

Next Step

Exercise 3: Using IValidatableObject custom validation