Validation Application Block - How to use validation metada class

539 views Asked by At

I'm using VAB to validate some classes with attributes and I'm using a metadata class to share the same validation among different classes. When i try to validate an object in the controller (btw i'm using asp.net mvc) the ValidationResults does not have errors and my entity should not be valid. But, ASP.NET MVC does his magic because ModelState.IsValid is false. I guess the problem is the way I'm doing the manual validations.

In Global.asax I'm loading the associations between the classes and metadata classes.

Global.ASAX

private static void RegisterMetadataExtensions()
{
    AssociatedMetadataTypeTypeDescriptionProvider typeDescriptionProvider;

    typeDescriptionProvider =
        new AssociatedMetadataTypeTypeDescriptionProvider(
            typeof(FooViewModel), typeof(FooMetadata));

    TypeDescriptor.AddProviderTransparent(typeDescriptionProvider,
        typeof(FooViewModel));

    typeDescriptionProvider =
        new AssociatedMetadataTypeTypeDescriptionProvider(
            typeof(FooCommand), typeof(FooMetadata));

    TypeDescriptor.AddProviderTransparent(
        typeDescriptionProvider, typeof(FooCommand));
}

Controller

[HttpPost]        
public ActionResult Action(FooViewModel vm)
{
    Validator<FooViewModel> validator =
        ValidationFactory.CreateValidator<FooViewModel>();

    ValidationResults res = validator.Validate(vm);

    //res.Count is 0

OR

    ValidationResults res = Validation.Validate<FooViewModel>(vm);

    //res.Count is 0

    //ModelState.IsValid is false
    if(ModelState.IsValid)

Any idea is welcome.

Thanks in advanced.

2

There are 2 answers

0
JamesDunlop On

For your VAB validator to hook into ASP.NET MVC's validation I think you would need to implement ModelValidatorProvider and wrap the VAB validation results as described here ... http://bradwilson.typepad.com/blog/2009/10/enterprise-library-validation-example-for-aspnet-mvc-2.html

2
podiluska On

I'm a big fan of the enterprise library, but I think a better way to do validation with MVC is to make your ViewModel implement IValidatableObject. That way, it automatically gets validated during the binding phase that sets ModelState.Isvalid