A named validation is named validator for a given type. Named validations can be invoked on objects by using their names. The following section shows creating and using named validations as well as saving named validations (in memory) for later use.

            // Create a named validation for Person
// Setup rules for the validation inside the setup method
var validation = new Validation<Person>("My_Person_Validation")
.Setup(v => v.IsNotNull(p => p.Name, "Name is mandatory.")
.IsGreaterThan(18, p => p.Age, "Age should be greater than 18.")
);

// Get a validation repository. You can create your own validation repositories or use the included ValidationRepository which is an in-memory repository
var validationRepository = new ValidationRepositoryFactory().GetValidationRepository();
validationRepository.Save(validation);

// Validate a person object using the named validation
var invalidPerson = new Person();
var validator = invalidPerson.ValidateUsing("My_Person_Validation");
Assert.IsFalse(validator.IsValid);


Notes on Named Validations:

  • The alias for the named validations should be unique per object type. It is possible to have a "My_Validation" named validation defined for both Person and Address. If no alias is given for a named validation is given, "Default_Validation" is assigned as the alias.
  • You can implement a custom repository for storing named validations. The default implementation is a thread-safe in memory implementation which uses a List<object> to store validations. (Implementation in ValidationRepository.cs, ValidationRepositoryFactory.cs)

 

Last edited Jan 3, 2011 at 2:03 PM by ashishsharmaait, version 3

Comments

No comments yet.