gpt4 book ai didi

c# - FluentValidation - 验证包含对象列表的 View 模型

转载 作者:IT王子 更新时间:2023-10-29 04:22:50 27 4
gpt4 key购买 nike

我正在一个包含复杂 View 模型的项目上试用 FluentValidation,我阅读了 documentation here但我不知道如何设置规则来验证在我的 View 模型中声明的对象列表。在我下面的示例中, View 模型中的列表包含 1 个或多个 Guitar 对象。谢谢

查看模型

 [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; }
}

View Model中使用的吉他类

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

查看模型验证器类

 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????


}
}

最佳答案

此代码已弃用:RuleFor(x => x.Guitars).SetCollectionValidator(new GuitarValidator());

这是新的:

RuleForEach(x => x.Guitars).SetValidator(new GuitarValidator());

关于c# - FluentValidation - 验证包含对象列表的 View 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21309747/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com