Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

c# - FluentValidation - Validating a View Model that contains a list of an Object

I am trying out FluentValidation on a project that contains complex view models and I read the documentation here but I don't see how to set up the rules to validate a list of objects declared in my view model. In my example below, the list in the view model contains 1 or more Guitar objects. Thanks

View Model

 [FluentValidation.Attributes.Validator(typeof(CustomerViewModelValidator))]
    public class CustomerViewModel
    {
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Display(Name = "Phone")]
        public string Phone { get; set; }

        [Display(Name = "Email")]
        public string EmailAddress { get; set; }

        public List<Guitar> Guitars { get; set; } 
    }

Guitar class used in View Model

public class Guitar
{
    public string Make { get; set; }
    public string Model { get; set; }
    public int? ProductionYear { get; set; }
}

View Model Validator Class

 public class CustomerViewModelValidator : AbstractValidator<CustomerViewModel>
    {


        public CustomerViewModelValidator()
        {
            RuleFor(x => x.FirstName).NotNull();
            RuleFor(x => x.LastName).NotNull();
            RuleFor(x => x.Phone).NotNull();
            RuleFor(x => x.EmailAddress).NotNull();
           //Expects an indexed list of Guitars here????


        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You would add this to your CustomerViewModelValidator

RuleFor(x => x.Guitars).SetCollectionValidator(new GuitarValidator());

So your CustomerViewModelValidator would look like this:

public class CustomerViewModelValidator : AbstractValidator<CustomerViewModel>
{
    public CustomerViewModelValidator()
    {
        RuleFor(x => x.FirstName).NotNull();
        RuleFor(x => x.LastName).NotNull();
        RuleFor(x => x.Phone).NotNull();
        RuleFor(x => x.EmailAddress).NotNull();
        RuleFor(x => x.Guitars).SetCollectionValidator(new GuitarValidator());
    }
}

Add the GuitarValidator would look something like:

public class GuitarValidator : AbstractValidator<Guitar>
{
    public GuitarValidator()
    {
        // All your other validation rules for Guitar. eg.
        RuleFor(x => x.Make).NotNull();
    }
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...