Introduction to Enterprise Library: Part V

In previous article, we had discussed about implementation of validators using Enterprise Library's Configuration Tool. In this article, we will look into validator's implementation using custom Code and end up with Message templates. Sometimes, the built-in validators might not serve our purpose. In those cases, we can create our own validating methods.

Open your Visual Studio 2008 and create a new console application, name it as CodeBasedVAB. Add required VAB dlls, which was specified in previous articles. Now, Go to program.cs and add this below class definition:

Validation through custom code is called as self validation. We need to decorate the class having self validation with [HasSelfValidation]. We had defined validation methods for checking negative salary and valid emp Ids with a Self Validation attribute as shown above.

Now, we will validate this Employee object in Main method as shown below:

Run the application, the output will be like this:

 

Now, we look into MessageTemplate attribute. All the validators discussed so far are having a MessageTemplate attribute. This attribute is used to set the validation message to be displayed on fail of its validation. By default, all validators will be having an in-built Message template. Like, default MessageTemplate for Range validator is “The length of the value must fall within the range "0" (Ignore) - "2" (Inclusive).”

We will see how to pass substitution values to MessageTemplate. Add this code as shown below:

Now, run the application. The output will be like this:

I am ending the things here. I am attaching source code for reference. In coming articles, we will go deep into this Application block. I hope this article will be helpful for all.

Next Recommended Readings