mit {CollectionIndex} kann man in einer FluentValidation Message den Index ausgeben.
Dieser beginnt aber mit 0, was für Entwickler normal ist, aber eben nicht für Anwender.
Daher kann man mit dieser ExtensionMethod den Index +1 setzen, womit er mit 1 anfangen würden.
Nachteil, man muss nach jeder .Message(„…“).IncrementCollectionIndexBy1() anhängen
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public static class IncrementCollectionIndexExtension { public static IRuleBuilderOptions<T, TProperty> IncrementCollectionIndexBy1<T, TProperty>(this IRuleBuilderOptions<T, TProperty> ruleBuilder) { return ruleBuilder.Configure(rule => { // A rule can only have a single message builder. // If it already has one, cache it and call it from within our new one below // (essentially chaining them together). rule.MessageBuilder = (context) => { if (context.MessageFormatter.PlaceholderValues.TryGetValue("CollectionIndex", out object index)) { if (index is int i) { i++; context.MessageFormatter.AppendArgument("CollectionIndex", i); } } return context.GetDefaultMessage(); //return rule.MessageBuilder?.Invoke(context) ?? context.GetDefaultMessage(); }; }); } } |
Login