Click here to Skip to main content
13,548,686 members
Click here to Skip to main content
Add your own
alternative version


56 bookmarked
Posted 12 Sep 2002
Licenced CPOL

Single Control Validation Solution

, 17 Sep 2002
Rate this:
Please Sign up or sign in to vote.
A single control to validate a .NET Web Form.

Sample Image - Validator.gif


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
                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, and I'll do my best to fix it. Also, if you have any comments, concerns, or suggestions, let me know.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Jamie Nordmeyer
United States United States
I'm a Software Architect, working for a telecom in Portland, OR. My specialties are C#, Win32 C/C++ programming, Visual Basic (6 and .NET), and ASP(.NET), XML/XSL, and database programming. I'm currently learning F#. Completely different than anything I've ever done, but very cool. I'm married to the most wonderful woman, have a beautiful daughter that I'm very proud of, and a step-son that's rocking in high school. I'm also a 2nd degree blackbelt in Olympic style (WTF) Taekwondo, and have trained in Brazilian Jiujitsu, Jeet Kun Do, Krav Maga.

You may also be interested in...


Comments and Discussions

GeneralFont size problem Pin
richiecode30-Jul-07 11:01
memberrichiecode30-Jul-07 11:01 
GeneralRe: Font size problem Pin
Jamie Nordmeyer30-Jul-07 12:42
memberJamie Nordmeyer30-Jul-07 12:42 
GeneralRe: Font size problem Pin
richiecode31-Jul-07 5:18
memberrichiecode31-Jul-07 5:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

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

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04-2016 | 2.8.180515.1 | Last Updated 18 Sep 2002
Article Copyright 2002 by Jamie Nordmeyer
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid