WinForms Validation Code

When trying out some of the new WinForms features I quickly set about seeing how validation in winforms had changed. Turns out it hasn’t 
 
You see, my history is in web development and as such I have enjoyed one of best features of ASP.NET 1.1, the validation controls. When I went to create my first WinForms application I was shocked that there were no equivalent controls for doing form validation. Instead you get the ErrorProvider component (extender control even?) that you can use along with the appropriate control and form events to display a little icon next to controls that need attention. Hmmm, not quite the same development experience as ASP.NET. So I went about devising a routine for validating forms in WinForms.
 
In the end all it is is a few IsValid() methods but I think it makes it fairly simple to setup validation code and use the error provider. First of all, there is an IsValid() method that takes the control to validate and a string to store any validation error message. It returns a boolean to indicate whether the control’s value is valid. The body is basically a large case statement (on the control’s name) containing the validation logic for each control. Simple enough.
 
This method is used in a couple of ways. Firstly it is used by universal handlers for the controls validating events (or other events if more apppropriate) to set the error provider message on the controls. Secondly it is used by an overload of the IsValid() method that is for validating the whole form, or any group of controls really.
 
The second IsValid() method takes a Control.ControlCollection and a StringCollection to return the validation messages in. It just loops through the controlCollection and calls the first IsValid() method for each of them. Fairly simple but as I said, it results in a fairly clean and as easy to maintain set of validation functions.
 
You can grab the code here.


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