当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Custom message with fluent validation collection

问题描述:

I am using the SetCollectionValidator for a generic collection. My collection is a list of:

public class Answer {

public string QuestionConst { get; set; }

public string QuestionName { get; set; }

public bool Required { get; set; }

public string Answer { get; set; }

}

I have the validation setup and working so when an item is invalid the error message is something like: "'QuestionName' must not be empty". I would like the error message to say something like "'The First Question' must not be empty." (where The First Question is the value for QuestionName for one of the items).

I guess my question is: Is it possible to use the value of a variable in the error message or property name?

网友答案:
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
      );
}

Fluent validation documentation: Overriding error message

I found this info in 1 minute :) Read documentation for this library, because there are very little information about it in web.

Additionally, you should use collection validator:

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

public class AnswersModel
{
    public List<Answer> Answers{get;set;}
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: