首页 > 解决方案 > 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 验证?

谢谢您的帮助

标签: asp.net-coreunobtrusive-validationfluentvalidation

解决方案


SSN 客户端:我怀疑您需要编写自定义客户端适配器。开箱即用的客户端支持非常有限,并且由于您的附加 When 子句,它可能不会触发。

当我必须自己构建时,我用它作为指南。

MainAddress 服务器端:在调用服务器端验证之前,它是否已填充到您的模型中?或者它是空的?如果没有定义明确的规则,我会期望验证器忽略它。有一条Null()规则可以应用于属性以确保它为空。


推荐阅读