Extending the .Net Validators
Been a while since I've had a .Net post. Haven't been doing to much development right now. Mostly maintenance work so haven't really be doing anything worthy of a post.But my co-workers and I have been working on a set of tools that we all use that we should standardize. No sense in all of us writing the same code. One of the biggest differences is how we all handle our input validation. I have been using all the built in RequiredFieldValidators (msdn), CompareValidators (msdn), and the occasional RegularExpressionValidator (mdsn) and others have been spinning their own solutions. So we all go together and hashed out what we all wanted out of our validation, and I ended up writing a custom validator that blended the options.
At first I was going to just try to extend the CompareValidator to add the data types that I/we wanted but that really isn't an option since you can't tap into the ValidationDataType that the control uses. So I ended up starting from scratch essentially and just extended the BaseValidator (msdn) and just wrote my own validate function. See below for code.
Option Strict On
Option Explicit On
Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Namespace CustomControls
Public Class myValidator
Inherits BaseValidator
Public Enum FormatTypes
PhoneNumber
SSN
DateTime
StrictAlpha
Alpha
Numeric
AlphaNumeric
ZipCode
URL
End Enum
Private _type As FormatTypes
'''
''' What kind of format do you want the data in
'''
Public Property DataType() As FormatTypes
Get
Return _type
End Get
Set(ByVal value As FormatTypes)
_type = value
End Set
End Property
Dim _isRequired As Boolean = False
Public Property Required() As Boolean
Get
Return _isRequired
End Get
Set(ByVal value As Boolean)
_isRequired = value
End Set
End Property
Protected Overrides Function EvaluateIsValid() As Boolean
Dim expression As String = ""
Dim stringToValidate As String = Me.GetControlValidationValue(Me.ControlToValidate)
Dim isValid As Boolean = False
If _isRequired And Trim(stringToValidate) = "" Then
isValid = False
ElseIf Not _isRequired And Trim(stringToValidate) = "" Then
isValid = True
Else
Select Case _type
Case FormatTypes.Email : expression = "^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}"
Case FormatTypes.PhoneNumber : expression = "((\(\d{3}\) ?)|(\d{3}[- \.]))?\d{3}[- \.]\d{4}(\s(x\d+)?){0,1}$"
Case FormatTypes.SSN : expression = "\d{3}-\d{2}-\d{4}"
Case FormatTypes.Alpha : expression = "^[a-zA-Z ,-.:/_?!']*$"
Case FormatTypes.AlphaNumeric : expression = "^[a-zA-Z0-9 ,-.:/_()?!]+$"
Case FormatTypes.DateTime : expression = "^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|
[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))
|(?:2[0-8]|1\d|0?[1-9]))([-./])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|
$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$"
Case FormatTypes.Numeric : expression = "^[0-9]*$"
Case FormatTypes.StrictAlpha : expression = "^[a-zA-Z]*$"
Case FormatTypes.URL : expression = "^(http\:\/\/[a-zA-Z0-9_\-]+(?:\.[a-zA-Z0-9_\-]+)*\.[a-zA-Z]{2,4}(?:\/[a-zA-Z0-9_]+)
*(?:\/[a-zA-Z0-9_]+\.[a-zA-Z]{2,4}(?:\?[a-zA-Z0-9_]+\=[a-zA-Z0-9_]+)?)?(?:\&[a-zA-Z0-9_]+\=[a-zA-Z0-9_]+)*)$"
Case FormatTypes.ZipCode : expression = "(\d{5}-\d{4})|(\d{5})$"
End Select
If Regex.IsMatch(stringToValidate, expression) Then
isValid = True
Else
isValid = False
End If
End If
Return isValid
End Function
End Class
End Namespace
So that is the class. There are some pretty hefty regular expressions in there. But don't let them scare you. You set them and forget them. I had to break the lines a bit to get them to look nice on the screen.
So to get it on the page you are going to need to register the namespace. Example below:
<%@ Register TagPrefix="vld" Namespace="CustomControls">
Once you've got it registered (you can put it in the web.config file as well if you don't want to declare it on every page) you can actually use the control. You can use it just like you would with the RequiredFieldValidator. See example below:
<vld:myValidator ID="cusEmail" DataType="Email" required="false" ControlToValidate="txtEmail" ErrorMessage="Enter valid email address" Display="dynamic" runat="Server">*</vld:myValidator>
And thats pretty much it. The DataType property will list all of the values you have defined in the code file. To add more data types you can add it to the formatType enum and just add the regEx to the case statement in the validate function and you are good to go.Labels: .NET
posted by Tom Becker at
8/20/2008
![]()

1 Comments:
your code is like dadaist poetry to me.
August 25, 2008 5:36 PM
Post a Comment
<< Home