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

zgi*_*rod 17 c# fluentvalidation

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

public class Answer {
  public string QuestionConst { get; set; }
  public string QuestionName { get; set; }
  public bool Required { get; set; }
  public string Answer { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Evg*_*vin 26

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
      );
}
Run Code Online (Sandbox Code Playgroud)

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

WithMessage(answer => $"This message references some other properties: Id: {answer.Id} Title: {answer.Title}"
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

public class AnswersModel
{
    public List<Answer> Answers{get;set;}
}
Run Code Online (Sandbox Code Playgroud)