Jaa


Single Member Validators

The Validation Application Block contains three validators that you can use to validate individual members of types, instead of validating the entire type using attributes or rule sets. While not a common scenario, this technique may be useful when integrating with other frameworks such as WPF and Windows Forms. The three validators are:

  • FieldValueValidator. Use this validator to validate a field of a type.
  • MethodReturnValueValidator. Use this validator to validate the return value of a method of a type.
  • PropertyValueValidator. Use this validator to validate the value of a property of a type.

For example, you can programmatically create a validator for an instance of a class named MyClass that validates the value of a property named MyProperty using a regular expression validator as shown here.

Validator propValidator = new PropertyValueValidator<MyClass>("MyProperty", 
                              new RegexValidator("some-regular-expression"));
MyClass myInstance = new MyClass();
myInstance.MyProperty = "Some value";
ValidationResults results = propValidator.Validate(myInstance);
'Usage
Dim propValidator As New PropertyValueValidator(Of MyClass)("MyProperty", _
                         New RegexValidator("some-regular-expression"))
Dim myInstance As New MyClass()
myInstance.MyProperty = "Some value"
Dim results As ValidationResults = propValidator.Validate(myInstance)

That second parameter to the constructor is the validator to use for the property value. You can also create a composite validator from a combination of validators, and specify this composite validator in the code above. A similar technique can be used with the FieldValueValidator and MethodReturnValueValidator.