This project has moved and is read-only. For the latest updates, please go here.

Set Validator for particular values inside an indexed Property?


Good afternoon,

I have another question regarding specifying a custom validator, particularly I have an IEumerable/Collection and I want to set a validator of type A for one of the entries and another validator of type B for again.. another entry in that collection (and basically ignore other entries).

This does not work (as it throws an exception saying 'Nested validators can only be used with Member Expressions.'):
this.RuleFor(teamProject => teamProject.Categories[categoryName]).SetValidator(validatorInstanceForCategoryWithProvidedCategoryName);
.. but how could/would I do that instead?



JeremyS wrote Sep 30, 2013 at 10:40 AM


The only way to do this really would be to expose the item you're indexing into as its own property, and then define a rule for this.

joergbattermann wrote Sep 30, 2013 at 11:25 AM

Hi Jeremy,

as the API is 3rd Party (in this case Microsoft's TFS Client API / Client object model) I cannot really modify this and writing a wrapper 'just' for validation purposes would mean extensive code-changes underneath.

Would it be possible to use/extend something like the existing .WithName("...") functionality for this?

joergbattermann wrote Sep 30, 2013 at 11:41 AM

(.. 'the API' being the instances with the properties I want to validate (e.g. 'teamProject.Categories' as mentioned above)

JeremyS wrote Sep 30, 2013 at 2:43 PM

In that case, for now your best bet would be to write a custom validator, but I'll try and implement this for a future release.

joergbattermann wrote Sep 30, 2013 at 9:03 PM

If there's anything I can do / provide / test upfront whenever you get to it, please let me know, happy to help in any way.

What would help is basically.. if the property to be validated is an IEnumberable<T> .RuleFor could optionally take a selector Func<TEnumerable, TResult> that returns the desired child-element to be validated (e.g. for NotNull(), or a custom sub-validator etc).

Often a .Contains() Validator for such IEnumerable<T>/ICollection<T> properties would be useful upfront, too.. taking either an instance of T as input paramater to check for and again.. such a selector for more arbitrary checks.

.. well that's what would come to my mind in terms of desired & useful functionality :)