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
);
}
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;}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With