Business Object Validation Using Validation Application Block - Self Validation Option - Enterprise Library 3.0
by David Hayden ( Sarasota Florida .NET C# SQL Server Developer ), Filed: Enterprise Library 3.0
I have talked about using the Validation Application Block in Enterprise Library 3.0 to validate your business objects in several tutorials:
As you may recall, the Validation Application Block comes with a library of validators that can be assigned to business object properties and fields to help validate a business object. There may be cases, however, where proper business object validation is complex and/or cannot be handled with the validators alone but you still want to use the Validation Application Block to provide consistent business object validation in your application. In cases like this, you can use Self Validation, which gives you full control of the validation and the same consistent use of the Validation Application Block.
Business Object Validation Using Self Validation
Self Validation of a business object can be configured using the configuration file or attributes. In this case, I will show it with attributes. Simply add a couple of attributes, HasSelfValidation and SelfValidation, defined in the Validation Application Block on your classes as well as a specific Validate Method, and you can use the Validation Application Block as normal for validation.
[HasSelfValidation]
public class Customer
{
[SelfValidation]
public void Validate(ValidationResults results)
{
// Add your own validation logic here.
// Add broken rules to results class
// to signify an invalid class.
// Do nothing if valid.
}
}
Below is an example of using Self Validation to validate the Customer Business Object:
[HasSelfValidation]
public class Customer
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
[SelfValidation]
public void Validate(ValidationResults results)
{
if (string.IsNullOrEmpty(_name))
{
results.AddResult(
new ValidationResult(
"Name cannot be null.",
this,
"Name",
null,
null
)
);
}
}
}
Customer validation using the Validation Facade Class in the Validation Application Block is the same:
Customer customer = new Customer();
customer.Name = null;
ValidationResults results = Validation.Validate(customer);
if (!results.IsValid) ...
Conclusion
Self Validation is a great solution for those cases where you need more control or flexibility of the business object validation but still want to use the Validation Application Block in your application.
Source: David Hayden ( Sarasota Florida .NET C# SQL Server Developer )
Filed: Enterprise Library 3.0