繁体   English   中英

具有流畅验证集合的自定义消息

[英]Custom message with fluent validation collection

我使用SetCollectionValidator作为泛型集合。 我的收藏是一个列表:

public class Answer {
  public string QuestionConst { get; set; }
  public string QuestionName { get; set; }
  public bool Required { get; set; }
  public string Answer { get; set; }
}

我有验证设置和工作,所以当一个项目无效时,错误信息是这样的:“'QuestionName'不能为空”。 我想错误消息说“'第一个问题'不能为空。” (其中第一个问题是其中一个项目的QuestionName的值)。

我想我的问题是:是否可以在错误消息或属性名称中使用变量的值?

public class AnswersModelValidator : AbstractValidator<AnswersModel>
{
   RuleFor(customer => customer.Text)
      .NotEmpty()
      .WithMessage("This message references some other properties: Id: {0} Title: {1}", 
        answer => answer.Id, 
        answer => answer.Title
      );
}

更新:在较新版本的FluentValidation中语法已更改:

WithMessage(answer => $"This message references some other properties: Id: {answer.Id} Title: {answer.Title}"

流畅的验证文档:覆盖错误消息

我在1分钟内发现了这个信息:)阅读这个库的文档,因为在网上关于它的信息非常少。

此外,您应该使用集合验证器:

public class AnswersModelValidator : AbstractValidator<AnswersModel> {
    public AnswersModelValidator() {
        RuleFor(x => x.Answers).SetCollectionValidator(new AnswerValidator());
    }
}

public class AnswersModel
{
    public List<Answer> Answers{get;set;}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM