gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:59:19 24 4
gpt4 key购买 nike

我将 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' 不能为空”。我希望错误消息显示类似“'The First Question' must not be empty.”之类的内容。 (其中第一个问题是其中一项的 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}"

Fluent validation documentation: Overriding error message

我在 1 分钟内找到了这个信息 :) 阅读这个库的文档,因为网络上关于它的信息很少。

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

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

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

关于c# - 具有流畅验证集合的自定义消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9739701/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com