Using Self-Validation
There are situations where you might want to have complete control over the validation logic but still leverage the foundation provided by the Validation Application Block. You can gain that level of control by using the "self-validation" feature supplied with the block. To create a self-validating class, you decorate the class with the
HasSelfValidation attribute and each method with the
SelfValidation attribute. This validation method must return void and accept a single input parameter of type ValidationResults. Inside the method, you can add any type of validation logic and set the ValidationResults properties (see Table 2) to appropriate values.
For example, here's an implementation of a class named Student with a
CheckStudentID() method that contains custom validation logic.
using System;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
namespace ValidationExample
{
[HasSelfValidation]
public class Student
{
public int StudentID;
[SelfValidation]
public void CheckStudentID(ValidationResults results)
{
// Compare the StudentID against some other value
if (StudentID > 100000)
{
ValidationResult result = new ValidationResult
("Incorrect ID", this, "StudentID", null, null);
results.AddResult(result);
}
}
}
}
Note the use of
HasSelfValidation and
SelfValidation attributes to indicate the self-validating class behavior. Inside the
CheckStudentID() method, you create a new ValidationResult object and add it to the ValidationResults collection when the
StudentID value is greater than 100000.
Again, the flexibility of the Validation Application Block becomes apparent when you realize that you can freely mix and match customized self-validation with the built-in attributed, programmatic, or configuration-based validation. In other words, adding the
SelfValidation attribute doesn't cause you to lose the ability to validate other class properties with the standard validation.
This article discussed the use of the Validation Application Block to meet common validation requirements, and provided examples showing how to use the Validation Block to validate simple primitive datatype values such as string, integer, and datetime variables. In addition, you saw the steps involved in creating reusable validation rules through application configuration files. Finally, the article showed how to create objects that are capable of performing self-validation. With this tool in your development arsenal, you should now rarely (if ever) need to spend time writing validation plumbing code in your applications.