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 “Required” attribute and “StringLength” attribute. These attributes belong to theSystem.ComponentModel.DataAnnotations namespace.

There four built-in attributes that you can for validation. :Required,  StringLength,  Range and 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 the article here.

  1. This is how the View looks like.

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

Image

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) %>

f 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. (Please 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.

Image

 

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.

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” type=”text/javascript”></script>

<script src=”/Scripts/MicrosoftMvcAjax.js” type=”text/javascript”></script>

<script src=”/Scripts/MicrosoftMvcValidation.js” type=”text/javascript”></script>

 If you are using Jquery

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

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

<script src=”/Scripts/MicrosoftMvcJQueryValidation.js” type=”text/javascript”></script>

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

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

image

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.

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.

Useful Unit Testing Research Tools

Microsoft Pex

A tool developed by Microsoft Research. It is an automated tool, which allows you to perform white-box type testing. Using Pex you can achieve higher code coverage. It also assists you with regression testing. 

You can download Pex from Microsoft Research. Pex is also included part of VS2010 Power Tools. 

Pex will generate all the necessary inputs and outputs by looking at your method. Then you can generate Unit Tests and run them as required. I highly recommend for methods with complex algorithms. You can also use Pex with other Unit Test frameworks such as nUnit, xUnit. 

Pex allows you to create Parameterized Unit Tests. When you download Pex, it comes with another tool called Moles, which allows you to replace any method with a delegate at test time. 

You can download Pex from here. 

CHESS

Another useful tool developed by Microsoft Research, which allows you to find and reproduce bugs (Heisenbugs)in concurrent and multithreaded programs. CHESS supports testing both managed and unmanaged code.

How CHESS track bugs?

In a nutshell, CHESS repeatedly exercise/run each threads multiple times with different interleaving. If the interleaving result an error CHESS will allow you to debug the error. 

[TestMethod]

[HostType(“Chess”)]

public void MyConcurrentThreadTestMethod()

{

                ……

}

You can make aware of your Unit Test that CHESS is integrated by just specifying the attribute, for example

CHESS allows you to locate the bug, reproduce it consistently, and then allow you to debug the issue.

For more information or to download CHESS please refer to the link here.