Custom TypeValidator and CompositeValidator

Basically, TypeValidator and CompositeValidator contain enough things to play with validation. There are a few virtual methods to override incase you want to add your logics:
  • BuildContextualValidationBuilders: Contextual validation builders are builders that will be added to the list of builders depend on the value of the validated object instance. Those contextual validation builders will be removed after validation so they will not affect later validations on different object instance.
  • CreateGenericBuilder: In ValidatorBuilder topic, we mentioned about the ValidationBuilder and 2 ways to change default validation builder type. Override this method is properly another way to change the run-time created ValidationBuilder. However, this way is not recommended unless you read through the code and know what you want to do.

Therefore, beside those things, I have know idea about potential reasons to create a custom TypeValidator :D

Also mentioned in Creating a new validator for your domain model:
  • TypeValidator: the basic validator for a type that allows you to create rules on properties. However, it will not validate nested object even though the validator type for nested object is registered with ValidatorFactory.
Example:
public class AddressValidator : TypeValidator<Address>
{    
     // Rules here in the constructor
}
  • CompositeValidator: works like TypeValidator. However, it will resolve the default validator for the type of nested complex object (even in the collection) and try to validate the nested object. The validator for nested object needs to be registered as default with ValidatorFactory in order to use this function.
Example:
public class UserValidator : CompositeValidator<User>
{
     // Rules here in the constructor    
}

Finally, if you want the new created validator type to be resolvable when calling ValidatorFactory.Current.GetValidatorFor(typeof(User)) for example, we need to register it as default validator:

ValidatorFactory.Current.Register(new UserValidator(), true);
//or
ValidatorFactory.Current.Register<UserValidator>(true);
And then

var validator = ValidatorFactory.Current.GetValidatorFor(typeof(User));
var results = validator.GetValidationResults(user);
if (results != null && results.Count() > 0)
{
    throw new Exception("Validation failed");
}
If you simply want to initialize the validator instance and validate some objects, you don't need to do the registration thing above:

var validator = new UserValidator();
var results = validator.GetValidationResults(user);
if (results != null && results.Count() > 0)
{
    throw new Exception("Validation failed");
}

Last edited Dec 14, 2011 at 8:08 AM by nvthoai, version 3

Comments

No comments yet.