Support for nested model and class validation with

2019-04-28 22:28发布

问题:

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.

回答1:

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();
        }

`