SIGN UP MEMBER LOGIN:    
ARTICLE

Introduction to Enterprise Library: Part IX

Posted by Sateesh Arveti Articles | Coding Best Practices February 23, 2009
This article explains about Implementation of Custom Validator using Validation Application Block.
Reader Level:
Download Files:
 

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.

Login to add your contents and source code to this article
share this article :
post comment
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Nevron Gauge for SharePoint
Become a Sponsor