Poor Man’s Validation

Does your validation drive you crazy? Are you writing too much validator code? Have you lost your sense of humor?

image

Well, not to worry because now, there’s a little hack to make Validation easier.

Lets say I had a Company class as defined by:

    public class Company
    {
        public string Title
        {
            get;
            set;
        }
    }

Now, say I wanted to add validation to this so that the

  • Title is Required
  • Title must be up to 10 characters
  • Title can only be Alpha and space

In order to achieve this quickly, you can add the System.ComponentModel.DataAnnotations.dll file to your project (Make sure its the latest one from Codeplex). Then update your class definition as follows:

    public class Company
    {
        [Required]
        [StringLength(10)]
        [RegularExpression("[A-Za-z\\s]+")]
        public string Title
        {
            get;
            set;
        }
    }

Now you can run the following code to validate your class instance as follows:

    //
    // Test instantiation
    ValidationContext vc = null;
    bool bCanCreate = false;
    List<ValidationResult> validationResults = new List<ValidationResult>();
    Company _company = new Company();

    //
    // Test 1 : Acceptable test undeo 10 characters and alpha.
    _company.Title = "The Title";
    vc = new ValidationContext(_company, null, null);
    bCanCreate = Validator.TryValidateObject(_company, vc, validationResults, true);
    Debug.Assert(bCanCreate == true);

    //
    // Test 2: Failure test 
    _company.Title = "32 Pan";
    vc = new ValidationContext(_company, null, null);
    bCanCreate = Validator.TryValidateObject(_company, vc, validationResults, true);
    Debug.Assert(bCanCreate == false);

    //
    // Test 3: Failure test 
    _company.Title = "";
    vc = new ValidationContext(_company, null, null);
    bCanCreate = Validator.TryValidateObject(_company, vc, validationResults, true);
    Debug.Assert(bCanCreate == false);

    //
    // Test 4: Failure test 
    _company.Title = "abcdefghijklm nopqrstuvwxyz";
    vc = new ValidationContext(_company, null, null);
    bCanCreate = Validator.TryValidateObject(_company, vc, validationResults, true);
    Debug.Assert(bCanCreate == false);

So now you’re bound to be validator approved.

image

Advertisements
Tagged , , , , ,

2 thoughts on “Poor Man’s Validation

  1. ActiveEngine Sensei says:

    Came upon your blog via StackOverflow. I like the technique you have discussed. I’m not sure if you’ve used jQuery client side validation, but Dave Ward has a series of posts that discuss their use with WebForms. I think your technique is a great match for what he shows. Here’ the link:

    http://encosia.com/2009/11/24/asp-net-webforms-validation-groups-with-jquery-validation/

    • aboutdev says:

      Thank you for your response ActiveEngine Sensei. I have seen and used JQuery and while I am no expert in JQuery just yet, I am learning more and more each day. The JQuery client side validation is definitely better than what traditional ASP.NET provides but as you point out yourself, it is client side. It is my belief that validation must happen client side for the benefit of the user and server side for the benefit of your code. The example I provided was an example (good or bad) for server side validation. Coupling that with the example from Dave Ward would be ideal in my opinion!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: