Validate one property constraints on an instance

Dec 17, 2008 at 9:26 PM
Hi !

First, kudos for the lib : I found it very cool and I'll definetely be using it (and trying to convince some colleagues too ;-))

I had just a question :

Is it possible to validate a property (I know that we can validate the whole object) while PropertyValidation is set to StateValidation ? I am trying to follow a BDD style of implementing my model, so I would need to test the constraints on a property at a time.

Thanks !
Coordinator
Dec 18, 2008 at 11:05 AM
Edited Dec 19, 2008 at 8:54 AM
Hi, thanks for the question.
If I understand your question, you want to test the validation applied to a property without actually invoking the property setter?
If yes, then you can do this, please see below, otherwise, you can also set the PropertyValidation mode to InterceptionValidation. This will result in the property setter throwing a ValidationException if the value is invalid.

There are extension methods on Type, PropertyInfo and ParameterInfo that enable you to resolve the validator.

So, you could do the following:
IValidator validator = typeof(Model).GetProperty("Email").ResolveValidator();
if (validator != null)
{
  try
  {
    validator.Invoke("testValue", new Model());
  }
  catch (ValidationException e) { ... }
}

Depending on what you want to test, you can inspect and/or flatten the caught ValidationException as described on the wiki.

A few points of interest:
  • If you apply more than one validator to the Email property these are contained within a compound validator which is why ResolveValidator() only returns a single validator. Compound validators don't impact the validation results.
  • The model passed to invoke is only neccessary if testing how custom validators which expect to query a Model instance behave. For testing the built-in validators you can just pass a new object() instead.
  • You could write IValidator validator = TypeOf<Model>.GetProperty(x => x.Email).ResolveValidator(); instead.
  • The ResolveValidator(...) methods are found in the TypeValidationRegistry, PropertyValidationRegistry and ParameterValidationRegistry classes alongside the Add and ReplaceValidation methods.
  • The above code can be refactored out into a test util class to enable you to write smaller test methods.
Happy you like the lib - always good to get some feedback! What type of app are you planning to use VA with? I'm interested to hear which UI frameworks would be good fo VA to integrate with.

Does this answer your question?
Dec 20, 2008 at 9:18 AM
Thanks for your well documented reply. I did not have the reflex to test the ResolveValidator method - my fault ;-)

I am planning to use it to validate my business rules on my domain model, not in a particular context (we have a lot of small project here and there).

I currently don't know with which UI fx I could use, sorry.

Oh and yes - it answered greatly to my question !