Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Support for nested model and class validation with ASP.NET MVC 2.0

I'm trying to validate a model containing other objects with validation rules using the System.ComponentModel.DataAnnotations attributes was hoping the default MVC implementation would suffice:

var obj = js.Deserialize(json, objectInfo.ObjectType);
if(!TryValidateModel(obj))
{
    // Handle failed model validation.
}

The object is composed of primitive types but also contains other classes which also use DataAnnotications. Like so:

public class Entry
{
    [Required]
    public Person Subscriber { get; set; }

    [Required]
    public String Company { get; set; }
}

public class Person
{
    public String FirstName { get; set;}

    [Required]
    public String Surname { get; set; }
}

The problem is that the ASP.NET MVC validation only goes down 1 level and only evaluates the properties of the top level class, as can be read on digitallycreated.net/Blog/54/deep-inside-asp.net-mvc-2-model-metadata-and-validation.

Does anyone know an elegant solution to this? I've tried xVal, but they seem to use a non-recursive pattern (http://blog.stevensanderson.com/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/).

Someone must have run into this problem before right? Nesting objects in your model doesn't seem so weird if you're designing a web service.

like image 764
Diep-Vriezer Avatar asked Jun 09 '10 13:06

Diep-Vriezer


1 Answers

I suggest looking into Fluent Validation from codeplex. The validation rules are contained in a separate class (similar to the way NHibernate and Fluent NHibernate work). One uses a lambda to specify the property to validate, supporting child properties.

`

public class MaintainCompanyViewModelValidator : AbstractValidator<MaintainCompanyViewModel>
    {
        public MaintainCompanyViewModelValidator()
        {
            RuleFor(model => model.Company.ShortName)
                .NotEmpty();
        }

`

like image 118
Rich Avatar answered Oct 16 '22 01:10

Rich