【发布时间】:2020-02-17 16:25:42
【问题描述】:
我正在使用 FluentValidation
public class AddressModel{
public string Street{get; set;}
public string City{get; set;}
public string State{get; set;}
public string Zip{get; set;}
public string Country{get; set;}
}
public class PersonModel{
public string FirstName {get; set;}
public string LastName {get; set;}
public string SSN {get; set;}
public AddressModel Address{get; set;}
public AddressModel MailingAddress{get; set;}
public int Type {get; set;}
}
public class AddressValidator : AbstractValidator<AddressModel>
{
public AddressValidator()
{
RuleFor(p=>p.Street).NotEmpty().WithMessage("Street is required");
RuleFor(p=>p.City).NotEmpty().WithMessage("City is required");
RuleFor(p=>p.Country).NotEmpty().WithMessage("Country is required");
RuleFor(p=>p.State).NotEmpty().WithMessage("State is required");
RuleFor(p=>p.Zip).NotEmpty().WithMessage("Zip code is required")
}
}
public class PersonValidator : AbstractValidator<PersonModel>
{
public PersonValidator()
{
RuleFor(p=>p.FirstName).NotEmpty().WithMessage("First name is required");
RuleFor(p=>p.LastName).NotEmpty().WithMessage("Last name is required");
RuleFor(p=>p.Address).SetValidator(new AddressValidator());
RuleFor(p=>p.SSN).NotEmpty().WithMessage("SSN is required").When(p=>p.Type ==1);
}
}
//启动
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddFluentValidation(fv =>
{
fv.RegisterValidatorsFromAssemblyContaining<Startup>();
});
当我在 UI 上单击保存时,我将获得以下必填字段:名字、姓氏和地址。填写完所有标记的必填字段并再次单击保存后,我将从服务器获取 MailingAddress 和 SSN 是必需的(我选择了 type = 1)。
如果我没有验证 MailingAddress,我需要做什么? 是否可以在客户端提供 SSN 验证?
感谢您的帮助
【问题讨论】:
-
你包括
_ValidationScriptsPartial.cshtml吗? -
是的。我包括在内。
标签: asp.net-core unobtrusive-validation fluentvalidation