Click here to Skip to main content
6,933,325 members and growing! (15,471 online)
Email Password   helpLost your password?
 
Web Development » Validation » Validation Controls     Intermediate

Validate user input in Windows Forms

By Jim Cai

You needn't write any code for control validation; just set a control's validation information at design-time and reduce maintenance workload.
C#.NET2.0, WinXP, WinForms, VS2005, Dev
Posted:26 Apr 2006
Views:63,627
Bookmarked:85 times
printPrint Friendly   add Share
      Discuss Discuss   Broken Article?Report  
27 votes for this article.
Popularity: 6.76 Rating: 4.72 out of 5
2 votes, 7.4%
1

2

3
3 votes, 11.1%
4
22 votes, 81.5%
5

Sample Image - Validator.gif

Introduction

I've been playing with ASP.NET since Beta 1, and I have to admit that I love it! What used to take days in traditional ASP can now be done in an afternoon. One of the few complaints that I have is ASP.NET's implementation of validators. While I certainly believe that validation controls extremely are time saving, I'm not really thrilled with the ones provided by Microsoft. They work great if you only have a few items to validate, but can become a chore to maintain, when there are many fields that need validation.

What I wanted was a single control that you could drop on to your form, that would handle all the validation for you. This way, you have one validator to maintain, not 10, or whatever. So I wrote this custom Validator control. Included in the download is the Validator control itself, its source code (don't run away screaming now, it's in VB.NET...), and 3 JavaScript files. I couldn't find an elegant way to use Microsoft's JavaScript files, and they didn't seem to support the DOM specs, so I wrote my own files. These need to be placed in your \inetpub\wwwroot\_vti_script directory. Validation.js is the main JavaScript file, which sets up some prototype functions, then links to one of the other two files depending on your browsers capability. ValidationDOM.js is, of course, for DOM compliant browsers (NS6.2+, IE5+). ValidationIE.js is for earlier versions of IE. I chose not to support early versions of Netscape, because there doesn't seem to be an elegant version of document.getElementById or document.all, and so Validation.js simply forces early versions of Netscape to use server side validation only.

Using the control

That being said, an explanation of its use is in order. The Validator control is derived from System.Web.UI.Webcontrols, and so has the standard properties of a web control. It also has 4 additional properties:

  • HeaderText As String

    The text that is displayed at the beginning of the error summary report.

  • ListStyle As Enum

    The style of bulleting that the error summary will use.

  • ClientSideScript As Boolean

    Produces code to allow validation at the client side.

  • UniqueErrors As Boolean

    Ensures that all strings in the errors collection are unique.

Once the Validator has been added to a page, you need to tell it what to validate. By either right-mouse clicking on the control, or looking at the designer verbs area just below the property window, you'll notice a menu/verb item marked 'Edit Fields'. A dialog then appears (as shown in the screenshot) allowing you to modify the control's collection of validations. Clicking on one of the buttons, adds a validator to the list, while clicking Remove will, of course, remove the selected item. All validation options share some common properties:

  • ControlToValidate As String

    The ID of the control to validate. The Validator control automatically appends any namespace on, so you just need the controls ID.

  • ErrorMessage As String

    The message to display if this validation proves invalid

  • ErrorMessageTarget As String

    The ID of the control where you want the ErrorMessage to be displayed. This is useful when you want the error message to appear somewhere on your form other than the summary.

  • ShowInSummary As Boolean

    Determines whether or not the ErrorMessage should be displayed in the summary. If this is false, and you set the ErrorMessageTarget property, then the ErrorMessage only appears at the ErrorMessageTarget.

Next is a summary of the additional properties of each of the validation types:

  • ReqFieldValidator - Verifies that a field has been modified
    • InitialValue As String

      If the controls value equals this when validated, then the validation is considered invalid.

  • RegExFieldValidator - Verifies that a fields value matches a specific pattern
    • RegularExpression As String

      The regular expression to use for validation.

    • CaseSensitive As Boolean

      If True, then case will matter. So, with a pattern of "[A-Z]{3}", AAA will be valid, but AaA will not.

    • MultiLine As Boolean

      Allows pattern matching to span more than one line of an HTML TextArea field.

  • RangeFieldValidator - Verifies that a field's value lies within a certain range
    • Minimum As String

      The minimum value. This is a string, because the Validator supports characters as well as numbers.

    • Maximum As String

      The maximum value.

    • Type As String

      The type of value that you'll be comparing. Possible values are String, Integer, Double, and DateTime

    • IgnoreCase As Boolean

      Whether to ignore case or not. If IgnoreCase is true, Minimum is A, and Maximum is Q, then f will be considered valid.

  • CompareFieldValidator - Verifies that a field's value compares a specific way to another value
    • Operator As Enum

      Determines what kind of comparison to perform. Possible values include (but are not limited to) DataTypeMatch, GreaterThan, LessThan, etc.

    • Type As String

      The type of value that you'll be comparing. Possible values are String, Integer, Double, and DateTime.

    • ControlToCompare As String

      The control to compare against.

    • ValueToCompare As String

      The value to compare against. If ControlToCompare and ValueToCompare both have values, then ControlToCompare takes precedence.

    • IgnoreCase As Boolean

      Whether to ignore case or not.

  • CustomFieldValidator - Verifies a field's value using a custom function
    • ClientSideFunction As String

      The name of the client side function to use in validating. This function must take a single parameter that is the control specified by the ControlToValidate property, and must return true for valid and false for invalid.

    • Name As String

      The Validator control raises a single event when server side validation takes place. This property allows you to distinguish between different custom validations.

In order to use server side validation for the CustomFieldValidator, you need to handle the CustomFieldValidation event of the Validator object. All CustomFieldValidator items that you've added to the control will route through this same event, so you need a way to distinguish between them. This is where the Name property of the CustomFieldValidator comes in hand. It is sent in the CustomFieldValidatorEventArgs class to the event handler.

Public Sub Validator1_CustomFieldValidation(ByVal sender As Object, _
         ByVal E As CP.Validator.CustomFieldValidatorEventArgs) _
         Handles Validator.CustomFieldValidation
    Select Case E.Name
        Case "IsEven"
            If CInt(DirectCast(E.ControlToValidate, _
                         TextBox).Text) Mod 2 = 0 Then
                E.IsValid = True
            Else
                E.IsValid = False
            End If
    End Select
End Sub

To add a validation to the control at run time, use the Validators collection of the control:

Validator1.Validators.Add(New ReqFieldValidator("txtName", 
                                       "Enter a name", ""))

I've tested it every way that I could think of, and it seems to be stable. However, since this is the control's first release to the public, you should expect bugs. If you run across any, please either post them here, or E-mail me directly at jamie.nordmeyer@mcgnw.com, and I'll do my best to fix it. Also, if you have any comments, concerns, or suggestions, let me know.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Jim Cai


Member

Location: China China

Other popular Validation articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 21 of 21 (Total in Forum: 21) (Refresh)FirstPrevNext
GeneralMy vote of 1 Pinmemberashney1:45 31 Dec '09  
GeneralPray tell, what does this article have to do with Windows Forms? Pinmembercjard3:11 14 Jun '09  
GeneralRe: Pray tell, what does this article have to do with Windows Forms? Pinmembertonymontana8211:29 15 Jul '09  
GeneralQuestion and suggestion PinmemberEvert Wiesenekker3:46 17 Apr '07  
GeneralThe Perfect Solution Pinmemberkooks2k21:18 31 Jan '07  
GeneralDataGridView PinmemberDanielRabe6:48 28 Nov '06  
Generalerror provider Pinmembershabonaa10:18 20 Oct '06  
GeneralThanks a lot! PinmemberPiotr Nogalski3:18 7 Oct '06  
GeneralRemoving icon, when disabling Control PinmemberdrJoene8:37 2 Oct '06  
GeneralNice, but... Pinmembertwesterd12:14 7 Jun '06  
Okay, this seems to be the #1 area I see application design errors (in my opinion). Long ago, especially with Web Apps, the validation had to be separate from the data object itself due the the nature of how web browsers communicated with data servers.

This is no longer the case, but the old design patterns refuse to leave. The UI, whether it is a web browser or a web form, should not know anything about validation... zip, zero, nada. Think about it, when a designer creates a data object (class), that class should set the validation rules about itself, not the textbox, or grid or whatever control is used to display the data.

You began the article with having to duplicate code, hence your validation control. But, you still must duplicate code for every form (browser or winform) that provides access to the data and your actual data object has a big gaping whole that allows bad data if you design a new form and miss "something" in the validation.

I suggest you read up on the IEditableObject, IPropertyChangeNotification, and IDataErrorInfo interfaces. Object classes should validate themselves and simply provide the information to the UI via these interfaces.

I do not have one line of validation code in the UI: zip, zero, nada on any form, yet the validation is robust. Furthermore, I create the validation for let's say 'Email Address', 'Credit Card Number', etc in ONE place in the business tier and the object itself simply calls IsValid(Email,textFromProperty, out message), if it fails the validation, then IDataErrorInfo is trigered for that property and the form displays the error without any validation code in the UI. Furthermore, since "rules" are consolidated in one location and the rule for, let's say 'Credit Card Number', changes, then I change it in ONE spot and I know every place that spawned from it(depends on it) updates without making any other "unecessary" changes to code.

My advice: never, ever place validation within the presentation tier - never... for the very same reasons you began the article with. Just because the old limitations have spawned bad habits that are still very popular does not mean they should be continued.

This is a perfect example of the "popular way" does not mean its the "right" way to go.

Having said all that, it was a nice article for what it was trying to do, but I personally would never validate data in this manner and I still rated your article high, it was done well.

Trevor
GeneralRe: Nice, but... I'm looking forward to your article... PinmemberPeter Hancock6:27 23 Aug '06  
GeneralRe: Nice, but... I'm looking forward to your article... PinmemberBrisbane20:56 13 Jun '07  
GeneralRe: Nice, but... PinmemberZoodor6:34 14 Sep '06  
GeneralRe: Nice, but... PinmemberPaul Menefee7:13 26 Sep '06  
GeneralRe: Nice, but... PinmemberPink Floyd8:19 2 Nov '06  
GeneralValidating UserControl PinmemberAli Youssef6:55 27 Apr '06  
GeneralRe: Validating UserControl Pinmemberdwegmann13:20 19 May '06  
GeneralRe: Validating UserControl PinmemberDanielRabe6:58 10 Oct '06  
QuestionIcon Pinmemberzizkam4:10 27 Apr '06  
AnswerRe: Icon PinmemberRick Engelking6:18 27 Apr '06  
JokeVery cool Pinmemberdavepermen22:18 26 Apr '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+PgUp/PgDown to switch pages.

PermaLink | Privacy | Terms of Use
Last Updated: 26 Apr 2006
Editor: Smitha Vijayan
Copyright 2006 by Jim Cai
Everything else Copyright © CodeProject, 1999-2010
Web18 | Advertise on the Code Project