asp.net-core - FluentValidation:如何显示客户端验证
问题描述
我正在使用 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 验证?
谢谢您的帮助
解决方案
SSN 客户端:我怀疑您需要编写自定义客户端适配器。开箱即用的客户端支持非常有限,并且由于您的附加 When 子句,它可能不会触发。
当我必须自己构建时,我用它作为指南。
MainAddress 服务器端:在调用服务器端验证之前,它是否已填充到您的模型中?或者它是空的?如果没有定义明确的规则,我会期望验证器忽略它。有一条Null()
规则可以应用于属性以确保它为空。
推荐阅读
- c# - c# 运算符 '??' 并作为'
- python - 从两个列表创建最小组
- uno-platform - 向情节提要添加重复行为和持续时间时出现 Wasm 异常
- java - Spring MVC 无法显示静态资源
- python-3.x - Pip 在 windows 的 cmd 中不被识别为外部命令
- excel - 返回列中第一个非空单元格中的值直接向左并向上
- azure-data-factory - 在 Azure 数据工厂中,如何在 Web UI 中创建由参数、字符串文字和函数组成的字符串表达式
- csv - 如何使用 sed 将列添加到 csv
- payment-gateway - 使用 ssl_recurring_flag 融合付款不起作用
- python - 无法在真实主机上使用 pyttsx3