MVC2 Validation step by step

Out of the box, MVC 2 framework supports both server side and client side validation. 

Server Side validation is based on System.ComponentModel.DataAnnotations, and Client Side validation is based on ASP.NET Ajax 4.0.

Both Server and Client Side validation are loosely coupled, and they are joined using JSON

You can also have multiple validator providers plugged in and run at the same time. You can remove the built-in validation providers and you can create your own once. 

Prior to MVC 2, MVC 1 used third party frameworks and plug-ins such as xVal to enable both client side and server validation. MVC 2 allows you to enable both server side and client side validation without having to use any third party frameworks or plug-ins. 

This article explains how to enable both server side and client side validation step by step.

 Enabling server side validation.

Lets start with the View Model. Please refer to the DemoModel code sample below.

There is a DisplayName attribute for each property. This attribute produces the name, which you should display within the View. Form validation point of view, it doesn’t add any value at all. What is important here is the “Requiredattribute and “StringLengthattribute. These attributes belong to the System.ComponentModel.DataAnnotations namespace.

 There four built-in attributes that you can for validation. They are

  • Required
  • StringLength
  • Range
  • RegularExpression.

If any of above attributes doesn’t fit for your requirements, then you can easily create your own validation attribute if needed. For more info please refer to

http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx

 public class DemoModel

    {

        [Required]

        [DisplayName(“Product Code”)]

        public string ProductCode { get; set; }

        [StringLength(10)]       

        [DisplayName(“Product Description”)]

        public string ProductDescription { get; set; }

        [Required]       

        [DisplayName(“Product Date”)]

        public string ProductDate { get; set; }

    }

1.       This is how the View looks like.

(Please not that greyed code samples are not relevant to MVC validation.) 

<%@ Page Title=”” MasterPageFile=”~/Views/Shared/Site.Master” Inherits=”System.Web.Mvc.ViewPage<ValidationDemo.Models.DemoModel>” %> 

<% using (Html.BeginForm()) { %>

        <div>

            <fieldset>

                <legend>Product Information</legend>

                <div>

                    <%= Html.LabelFor(m => m.ProductCode)%>

                </div>

                <div>

                    <%= Html.TextBoxFor(m => m.ProductCode) %>

                    <%= Html.ValidationMessageFor(m => m.ProductCode) %>

                </div>               

                <div>

                    <%= Html.LabelFor(m => m.ProductDescription) %>

                </div>

                <div>

                    <%= Html.TextBoxFor(m => m.ProductDescription) %>

                    <%= Html.ValidationMessageFor(m => m.ProductDescription) %>

                </div>

                <p>

                    <input type=”submit” value=”Submit” />

                </p>

            </fieldset>

        </div>

    <% } %>

 You can see that I’m deriving from ValidationDemo.Models.DemoModel. So my View will be strongly typed and I can bind to the Model properties using m => m.ProductCode etc.

The value that enter to the ProductCode text box is bound to the value of the Model using <%= Html.TextBoxFor(m => m.ProductCode) %>

 The validation message is displayed using the html helper extension.

<%= Html.ValidationMessageFor(m => m.ProductCode) %> 

If you remove this line, your validation will still work, however no messages will be displayed. 

Importantly you must ensure that your form which require validation is placed in between <% using (Html.BeginForm()) {  } tags. (See above)

2.       One last thing to remember is that you need an action method within your Controller to be able to execute your form POST. You must also pass the model to your action method, as a parameter. 

    public class ValidationController : Controller

    {

        public ActionResult Demo()

        {

            return View();

        }

        [HttpPost]

        public ActionResult Demo(DemoModel model)

        {

            return View();

        }    

    }

3.       Now when you click on Submit button, server side validation will trigger and the error messages are displayed.

a

4.    Using ValidationSummaryControl

       If you need the validation summary control (most of you do), you have to add the following helper extension method to the View. You can add this helper method anywhere you like (within the View). 

       <%= Html.ValidationSummary(false, “Product creation was unsuccessful. Please correct the errors and try again.”) %>   

 The first argument (excludePropertyErrors: true/false) specifies whether you want display list of error underneath the ValidationSummaryControl.

b

Enabling client side validation. 

MVC 2, uses Microsoft AJAX 4.0 as the default client side library. You can also use the JQuery version of the validation library. It is in MVC 2 Futures project. You can download it from MVC2 Future library.

1.       Ensure you reference three JS files within your application.

 

If you are using MS Ajax:

<script src=”/Scripts/MicrosoftAjax.js”></script>

<script src=”/Scripts/MicrosoftMvcAjax.js”></script>

<script src=”/Scripts/MicrosoftMvcValidation.js”></script>  

If you are using Jquery

<script src=”/Scripts/jquery-1.3.2.min.js”></script>

<script src=”/Scripts/jquery.validate.min.js”></script>

<script src=”/Scripts/MicrosoftMvcJQueryValidation.js”></script> 

Within your View, before the <% using (Html.BeginForm()) { %> statement, you need to add the code: <% Html.EnableClientValidation(); %> 

  1. That’s it. Now run the app. You can see the client side validation in action.

c

If it is still not working, ensure the browser does not disable your JavaScript by default. For example in FireFox you need to ensure both Java and Javascript is not disabled. To be honest I don’t know why Java needed to be disabled. Please let me know if anyone finds out.

 Tweaks

Enabling Validation Summary Control for client side. 

Out of the box Validation Summary Control does not work for client side validation. For example you cannot display validation summary error massagers, within the Validation Summary Control during client side user interactions. To enable this you can implement a solution, which is described in the post here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s