Best way to get a property index in ErrorMessage
See original GitHub issueI’m somewhat struggling with getting the path and in case of collections index of a validated property in the ErrorMessage
.
I’m using this wonderful library to validate requests coming into Azure functions and I very much do want to return the whole JSON path and index instead of just a property name.
I’ve managed to do so with path using some extension methods to extract the JsonProperty
attribute (or fall back to a reflected property name) and passing that to the constructors of my validators and to WithName
/WithMessage
like this .WithName(x => CreatePath(x.GetPropertyJsonName(nameof(x.Id))))
.
I do have a problem with extracting indexes from collections though.
Having a parent validator PermissionValidator
with a rule:
RuleForEach(x => x.Interests)
.SetValidator(x => new InterestValidator(CreatePath(x.GetPropertyJsonName(nameof(x.Interests)))));
Where Interests
is of type List<Interest>
defined like
[Serializable]
[DataContract]
public class Interest
{
[DataMember, JsonProperty("id")]
public string Id { get; set; }
[DataMember, JsonProperty("name")]
public string Name { get; set; }
}
Is it possible to include the index of the currently validated Interest
object in the message coming from InterestValidator
?
So instead of getting a message saying permission.interest.name cannot be empty
it would be permission.interest[0].name cannot be empty
.
Sorry if it’s a dumb question, this is my first time using FluentValidation
and I can’t really find any examples of this behavior.
Issue Analytics
- State:
- Created 5 years ago
- Comments:11 (7 by maintainers)
Top GitHub Comments
So I was thinking something like this:
And just to clarify, the instance being validated is accessible from the MessageBuilder’s context (
context.Instance
)