ZenArchitect.NL (Henk van Dijken)

the art of model-driven code generation

Archive for the ‘Factory Design Pattern’ tag

Simple Validation Rules Engine

without comments

Sometimes, you want to do some simple validation. For example, data should not exceed the reserved storage size for the field in the database.

image

In this example CustomerName must be less than 10 characters. So, the client code should look like this:

Customer customer = new Customer();

// customer name must be less than 10 characters
customer.CustomerName = this.textBox1.Text;

// Validation facade
ValidationResults results = Validation.Validate<Customer>(customer);

// populate listbox with validation results
foreach (ValidationResult result in results)
{
    this.listBox1.Items.Add(result.Message);
}

The customer name is filled with input from a textbox. The complete customer object is validated using a validation facade. Finally, a list box is populated with the validation results.

Use of a facade simplifies use of validation in the client. The facade itself looks like this:

public static class Validation
{
    public static ValidationResults Validate<T>(T validationobject)
    {
        Validator<T> validator = ValidationFactory.CreateValidator<T>();
        ValidationResults results = validator.Validate(validationobject);

        return results;
    }
}

But wait! This looks exactly like the Validation Application Block. That’s a coincidence!

Indeed. Since the callings are similar you easily can replace the plumbing with the real stuff later on if you want.

But be aware that there is a small difference. This simplified version does not use attributes, but self validation by implementing an ISelfValidation interface.

public interface ISelfValidation
{
    void Validate(ValidationResults results);
}

The object in question implements ISelfValidation as follows:

class Customer : ISelfValidation
{
    public string CustomerName { get; set; }

    public void Validate(ValidationResults results)
    {
        int maxLength = 10;
        string validationString = CustomerName;

        ValidateStringLength(results, validationString, maxLength);
    }

    // this can be put into a helper class if you want
    private static void ValidateStringLength(ValidationResults results, string validationstring, int maxlength)
    {
        if (validationstring.Length > maxlength)
        {
            results.Add(new ValidationResult(String.Format("Length must be less than {0}", maxlength)));
        }
    }
}

This way simple validation becomes very easy. So, kids please do try this at home.

Download(s) : [Download not found]

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Written by Henk van Dijken

May 6th, 2010 at 8:31 pm