Introduction to Enterprise Library: Part IX

In previous article, we had discussed about VAB adapter for WCF. In this article, we will look into creation of custom validator.

Create a new Class Library in VS 2008 and name it as CustomValidators. Now add the following dlls present in Enterprise Library installation folder:

  • Microsoft.Practices.EnterpriseLibrary.Common,
  • Microsoft.Practices.EnterpriseLibrary.Validation.Validators and finally
  • System.Configuration.

Now, delete existing class file in the project. We need to add two classes to the project, one is for the validator definition and other is validator's attribute definition. Add a class file named as EmployeeValidator.cs with below code:

using Microsoft.Practices.EnterpriseLibrary.Validation;

using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;

using Microsoft.Practices.EnterpriseLibrary.Validation.Configuration;

using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

using System.Collections.Specialized;

 

namespace CustomValidators

{

    [ConfigurationElementType(typeof(CustomValidatorData))]

    public class EmployeeValidator:Validator<string>

    {

      private string joinedDt;

 

        public EmployeeValidator(NameValueCollection attributes) : base(null, null)

        {

            joinedDt = attributes.Get("JoinedDate").ToString();

        }

 

        public EmployeeValidator(string joinedDt)

            : this(joinedDt, null, null)

        {

        }

 

        public EmployeeValidator(string joinedDt, string messageTemplate)

            : this(joinedDt, messageTemplate, null)

        {

        }

 

        public EmployeeValidator(string joinedDt, string messageTemplate, string tag)

            : base(messageTemplate, tag)

        {

            this.joinedDt = joinedDt;

        }

 

 

        protected override void DoValidate(string relievedDt, object currentTarget, string key, Microsoft.Practices.EnterpriseLibrary.Validation.ValidationResults validationResults)

        {

            if (DateTime.Parse(relievedDt) < DateTime.Parse(joinedDt))

            {

                string message = string.Format(this.MessageTemplate, relievedDt, joinedDt);

                this.LogValidationResult(validationResults, message, currentTarget, key);

            }

        }

 

        protected override string DefaultMessageTemplate

        {

     get { return "Relieved Date {0}is not valid for Joined Date {1}"; }

        }

    }

}

Here, we had implemented Validator class in our code. We need to add [ConfigurationElementType(typeof(CustomValidatorData))] to the class. Than, we added few constructors followed by implementation DoValidate method. In this method, we need to write validation code and return results back. This method checks whether the relievedDate is greater than JoinedDate or not for an employee.

Now, add another class file named as EmployeeValidatorAttribute.cs with below code:

using Microsoft.Practices.EnterpriseLibrary.Validation;

using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;

 

namespace CustomValidators

{

    public class EmployeeValidatorAttribute : ValidatorAttribute

    {

        private string joinedDt;

 

        public EmployeeValidatorAttribute(string joinedDt)

        {

            this.joinedDt = joinedDt;

        }

 

        protected override Validator DoCreateValidator(Type targetType)

        {

            return new EmployeeValidator(joinedDt);

        }

    }

}

Here, we had implemented ValidatorAttribute class in our code.  Finally, we had implemented DoCreateValidator method; this will create an instance of the validator with passed parameters.

Now, we need to test this validator. So, create a new Console application named as CustomValidatorsClient with below code in program.cs:

using Microsoft.Practices.EnterpriseLibrary.Validation;

using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;

using CustomValidators;

namespace CustomValidatorsClient

{

    class Program

    {

        static void Main(string[] args)

        {

            Employee objEmp = new Employee();

            objEmp.EmpID = 10;

            objEmp.RelievedDt = "01-JAN-2008";

            Validator<Employee> validator = ValidationFactory.CreateValidator<Employee>();

            ValidationResults results = validator.Validate(objEmp);

            foreach (ValidationResult res in results)

            {

                Console.WriteLine(res.Message);

            }

            Console.ReadLine();

        }

    }

    class Employee

    {

        public int EmpID { get; set; }

        [EmployeeValidator("02-AUG-2008")]

        public string RelievedDt { get; set; }

    }

}

We need to add reference to VAB dlls and our custom Validator dll also. Run the application, the output will be like this:

Steps to create our own Validator:

  • Write a class derived from Validator<T> or existing validators like DomainValidator.
  • Include required properties and constructors.
  • Override DoValidate method and call LogValidationResult method on fail of validations.
  • Override DefaultMessageTemplate property and include the message need to be displayed, if MessageTemplate attribute is not defined by the client.
  • Apply ConfigurationElementType to the class having reference to typeof(CustomValidatorData) in it.
  • Write a class derived from ValidatorAttribute with desired constructors and properties.
  • Override DoCreateValidator method. This should return an instance of the validator with required attribute values.
  • Build the Validator.
  • Add the reference of the custom validator in the client.

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.

Up Next
    Ebook Download
    View all
    Learn
    View all