Does your validation drive you crazy? Are you writing too much validator code? Have you lost your sense of humor?
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.
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/
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!