There are times when you don’t find a solution for a validation you need inside Validation Application Block validators. When this is happening Self Validation can help you to keep using VAB and gaining all its abilities. This post will explain how to use Self Validation in VAB.

What is Self Validation?

Self validation gives you the ability to implement validation logic inside the class you want to validate. When you have a complicated validation or your validation logic can’t be performed using the VAB validators you can apply this method.

How to use Self Validation?

The first thing to do when you want to indicate that a class has self validation is to decorate the class with a HasSelfValidation attribute. Then you decorate every self validation method with the SelfValidation attribute. The method signature need to be void and take only one instance of ValidationResults as parameter. This collection will be updated inside the method if the validation failed.

As you can see this is only an example and I could have used the regular VAB validators to achieve the same impact.

The SelfValidation attribute can also be used within a specific rule set by providing to it the rule set name as parameter. When we want to use the self validation logic we use it as we used all the other validators in VAB. For example:

Summary

I use a lot the the Validation Application Block as a validation framework. When I get stuck with complicated validations or the supplied validators can’t help me then I use the self validation feature. It is very simple and easy to apply. In the post I showed how to use it in code. I hope you will find it helpful.