19

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?

1
  • That should be implemented into the collection object, not the single item (which doesn't and shouldn't know how many siblings it has) Commented Mar 22, 2012 at 8:28

1 Answer 1

28
+25
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;}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.