ASP.NET MVC and Enterprise Library Validation Application Block

Previous ASP.NET MVC Tutorials:

 

We have been playing with input validation in the previous ASP.NET MVC Tutorials. With the new ModelState.AddModelError functionality we have a really cool way to provide feedback to the user on errors in his/her input. One of the cool offerings from Microsoft Patterns & Practices is the Enterprise Library Validation Application Block to help with validating your custom classes. In this tutorial I will show you a simple way ( one way ) to integrate the Validation Application Block with ASP.NET MVC.

 

 

Validation Application Block Tutorials

If you are not up to speed on the Validation Application Block, you can check out my previous Enterprise Library Tutorials:

You can also check out the following Enterprise Library Screencasts:

 

 

Enterprise Library Assemblies Referenced

At a minimum you need to reference the following 3 Enterprise Library assemblies in you ASP.NET MVC Application:

  • Microsoft.Practices.EnterpriseLibrary.Common
  • Microsoft.Practices.EnterpriseLibrary.Validation
  • Microsoft.Practices.ObjectBuilder2

 

 

Validation Validator Attributes on Custom Class Properties

The Enterprise Library Validation Application Block has numerous validator attributes that you can add to your custom class properties. You can also keep your classes validation ignorant ( Plain Old CLR Objects ) and add the validation in your configuration file. However, let's just stick with attributes for this quick example. Such validation validator attributes you can use are:

  • ContainsCharactersAttribute
  • DateTimeRangeValidatorAttribute
  • DomainValidatorAttribute
  • EnumConversionValidatorAttribute
  • NotNullValidatorAttribute
  • PropertyComparisonValidatorAttribute
  • RangeValidatorAttribute
  • RegexValidatorAttribute
  • StringLengthValidatorAttribute
  • etc...

A lot of cool options. I am going to keep this simple and just use the RegexValidatorAttribute to validate an email address on our trivial Customer's Email Property:

 

public class Customer
{
    public string Name { get; set; }

    [RegexValidator(@"^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$",
        MessageTemplate="Email invalid")]
    public string Email { get; set; }
}

 

 

ASP.NET MVC Validation Using Validation Application Block

The end result I am looking for is that when a user enters an incorrect email address in the Email TextBox, they are presented with an error such as:

 

ASP.NET MVC Enterprise Library

 

You can use the Validation Application Block in many ways. You can use the decorator pattern with your data access object or repository. You could inject a validation service into your controller. I am going to show it the simplest way - using the Validation Facade Class in the controller to validate the Customer Class and return a ValidationResults Collection that we can query for IsValid and enumerate through any errors.

Here is the simple Controller Action:

 

public ActionResult Save()
{
    Customer customer = new Customer();

    UpdateModel(customer, new[] { "Name", "Email" });

    ValidationResults results =
        Validation.Validate<Customer>(customer);
    
    if (!results.IsValid)
    {
        AddValidationResults(results, ViewData.ModelState);
        return View(customer);
    }

    return RedirectToAction("...");
}

 

I use UpdateModel to populate the Customer instance with the form values and then call Validation.Validate and pass it the Customer instance to validate. I query to see if the customer instance is valid, and if not, add the validation results to the ModelState and re-display the view with the errors.

The AddValidationResults Method just copies the ValidationResults to the ModelState via ModelState.AddError:

 

private static void AddValidationResults(ValidationResults results,
                ModelStateDictionary modelState)
{
    foreach (ValidationResult result in results)
        modelState.AddModelError(
            result.Key,
            result.Target.GetPropertyValue(result.Key),
            result.Message);
}

 

The gotcha with the Validation Application Block is getting the erroneous value being validated so we can display it back to the user on the form. The ValidationResult Class has a Target Property with the object being validated ( customer instance ), but not the property's value. We can create a quick extension method that uses a bit of reflection to get the value of these simple types. This isn't production code, just example code :) Notice I am using this extension method in the code above: results.Target.GetPropertyValue ...

 

public static object GetPropertyValue(this object obj,
                string propertyName)
{
    PropertyInfo property = obj.GetType().
            GetProperty(propertyName);
    
    return property.GetValue(obj, null);
}

 

Another way to accomplish the same thing is to just pass in the FormCollection to AddValidationResults and get the erroneous value from the collection of form values. That avoids the reflection, etc.

 

 

Conclusion

The Enterprise Library Validation Application Block is just another way of implementing input validation in your ASP.NET MVC Web Applications. Hopefully this tutorial gives you some ideas. Check out Patterns & Practices Guidance for other Patterns & Practices Tutorials and Screencasts.

David Hayden

 

posted on Wednesday, September 10, 2008 9:45 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices