Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 803
zgirod Avatar asked Mar 16 '12 15:03

zgirod


1 Answers

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
      );
}

UPDATE: syntax changed in newer version of FluentValidation:

WithMessage(answer => $"This message references some other properties: Id: {answer.Id} Title: {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;}
}
like image 173
Evgeny Levin Avatar answered Sep 29 '22 23:09

Evgeny Levin