Tag Archives: code example

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

Advertisement
Tagged , , , , ,