【问题标题】:FluentValidation: How to show client-side validationFluentValidation:如何显示客户端验证
【发布时间】: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


【解决方案1】:

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

当我必须自己构建时,我使用 this 作为指导。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 2012-09-25
    • 2015-12-04
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    相关资源
    最近更新 更多