skip to the main content area of this page
Patterns and Practices

 

ASP.NET MVC Sharp Architecture and Validation Application Block from Enterprise Library


The other day we were discussing changes to the Sharp Architecture CORE to decouple it from NHibernate Validator in case you did not want to use NHibernate Validator for validation of your domain entities.

The result was a number of interfaces being added to CORE for pluggable validation and an NHibernate Validator implementation being moved to a separate assembly.

As a proof of concept I created an implementation for use with the Enterprise Library Validation Application Block. This won't be added to the Sharp Architecture Project, but I thought I would provide the code here that you can tweak and improve just in case you may want to use the Validation Application Block.

 

Sharp Architecture Validation Provider for Validation Application Block

There are only two classes. The first is the provider itself and the second is essentially a DTO with the validation results. I tried to stay consistent as possible with the provider for NHibernate Validator.

 

EntLibValidator.cs

 

public class EntLibValidator : IValidator

{

    public bool IsValid(object value)

    {

        Check.Require(value != null, "value to IsValid may not be null");

 

        return DoValidation(value).IsValid;

    }

 

    public ICollection<IValidationResult> ValidationResultsFor(object value)

    {

        Check.Require(value != null, "value to ValidationResultsFor may not be null");

 

        var errors = DoValidation(value);

 

        return CollectionOf(errors);

    }

 

    protected virtual ValidationResults DoValidation(object value)

    {

        var factory = ValidationFactory.CreateValidator(value.GetType());

        return factory.Validate(value);

    }

 

    protected static ICollection<IValidationResult> CollectionOf(IEnumerable<ValidationResult> errors)

    {

        var results = new List<IValidationResult>();

 

        foreach (var error in errors)

            results.Add(new ValidatorResult(error));

 

        return results;

    }

}

 

 

ValidatorResult.cs

 

public class ValidatorResult : IValidationResult

{

    public Type ClassContext { get; protected set; }

    public string PropertyName { get; protected set; }

    public string Message { get; protected set; }

 

    public ValidatorResult(ValidationResult result)

    {

        Check.Require(result != null, "result may not be null");

 

        ClassContext = result.Target.GetType();

        PropertyName = result.Key;

        Message = result.Message;

    }

}

 

 

For more information on using the Enterprise Library Validation Application Block with the ASP.NET MVC Framework:


Tags: EnterpriseLibrary, EnterpriseLibrary4, MVC, NHibernate, ValidationApplicationBlock


Topics



 

Popular Tags



Recent Links