Click here to Skip to main content
15,879,239 members
Articles / Web Development / ASP.NET
Article

Single Control Validation Solution

Rate me:
Please Sign up or sign in to vote.
4.78/5 (6 votes)
17 Sep 2002CPOL5 min read 184.3K   639   56   41
A single control to validate a .NET Web Form.

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.

VB
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:

VB
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
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.

Comments and Discussions

 
GeneralCustomFieldValidator at runtime Pin
richiecode30-Aug-07 9:42
richiecode30-Aug-07 9:42 
GeneralRe: CustomFieldValidator at runtime Pin
Jamie Nordmeyer30-Aug-07 9:45
Jamie Nordmeyer30-Aug-07 9:45 
GeneralValidating a group of elements Pin
richiecode31-Jul-07 6:26
richiecode31-Jul-07 6:26 
GeneralRe: Validating a group of elements Pin
Jamie Nordmeyer31-Jul-07 6:31
Jamie Nordmeyer31-Jul-07 6:31 
GeneralRe: Validating a group of elements Pin
richiecode31-Jul-07 6:38
richiecode31-Jul-07 6:38 
GeneralFont size problem Pin
richiecode30-Jul-07 11:01
richiecode30-Jul-07 11:01 
GeneralRe: Font size problem Pin
Jamie Nordmeyer30-Jul-07 12:42
Jamie Nordmeyer30-Jul-07 12:42 
GeneralRe: Font size problem Pin
richiecode31-Jul-07 5:18
richiecode31-Jul-07 5:18 
GeneralUpdate coming soon! Pin
Jamie Nordmeyer14-Nov-06 10:22
Jamie Nordmeyer14-Nov-06 10:22 
GeneralRe: Update coming soon! Pin
Manish Pansiniya27-Nov-06 2:35
Manish Pansiniya27-Nov-06 2:35 
GeneralRe: Update coming soon! Pin
Jamie Nordmeyer27-Nov-06 5:23
Jamie Nordmeyer27-Nov-06 5:23 
GeneralGreat! Pin
T1TAN1-Oct-06 22:31
T1TAN1-Oct-06 22:31 
GeneralRe: Great! Pin
Jamie Nordmeyer2-Oct-06 4:25
Jamie Nordmeyer2-Oct-06 4:25 
QuestionCSS Help Pin
asifrazach24-Aug-06 5:36
asifrazach24-Aug-06 5:36 
AnswerRe: CSS Help Pin
Jamie Nordmeyer24-Aug-06 7:06
Jamie Nordmeyer24-Aug-06 7:06 
GeneralRe: CSS Help Pin
asifrazach24-Aug-06 7:12
asifrazach24-Aug-06 7:12 
GeneralRe: CSS Help Pin
asifrazach24-Aug-06 8:16
asifrazach24-Aug-06 8:16 
GeneralRe: CSS Help Pin
Williamgf28-Aug-06 6:26
Williamgf28-Aug-06 6:26 
GeneralRe: CSS Help Pin
Jamie Nordmeyer28-Aug-06 6:43
Jamie Nordmeyer28-Aug-06 6:43 
GeneralClient validation doesn't work Pin
rugrats30-Mar-05 20:48
rugrats30-Mar-05 20:48 
GeneralRe: Client validation doesn't work Pin
Jamie Nordmeyer31-Mar-05 5:39
Jamie Nordmeyer31-Mar-05 5:39 
QuestionLocalization Integration? Pin
scubaduba6-Jan-05 20:33
scubaduba6-Jan-05 20:33 
AnswerRe: Localization Integration? Pin
Jamie Nordmeyer7-Jan-05 4:50
Jamie Nordmeyer7-Jan-05 4:50 
Generalproblem with text box validation Pin
Member 15710164-Dec-04 0:06
Member 15710164-Dec-04 0:06 
GeneralRe: problem with text box validation Pin
Jamie Nordmeyer6-Dec-04 5:15
Jamie Nordmeyer6-Dec-04 5:15 

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.