Introduction
This article provides the readers code on how to create a custom validator control that does zip,phone and email validation all in one, by specifying a property. Thought of sharing it with other code project readers to get feedback and also provide users with a ready control.
Background
While working on a project for one of my clients, I had to create a standard form with zip,phone, email and other contact information. I had to validate the zip,email and phone for blanks and regular expressions. I started out by creating 2 controls a required field validator and regular expression validator, though the validation worked fine, the rendering was bad especially when checking for the regular expression it would show a blank and then the message, the blank being the reqd field validator.
The client was against my using javascript and so inorder to remove the gap and have only one validator control that does both i created a custom validator control and that got me what i wanted.
Using the code
In order to create a custom control, you would start with creating a class file, in this example it would be CustomZipValidator.vb and place it in the app code folder. The code in the class file is shown below, this class would inherit from the BaseValidator class and would override the EvaluateIsValid() method.
'Inherits the base validator
Public Class CustomZipPhoneEmailValidator
Inherits BaseValidator
'Override the EvaluateIsValid
Protected Overrides Function EvaluateIsValid() As Boolean
Dim value As String = Me.GetControlValidationValue(Me.ControlToValidate)
If (value.Equals(String.Empty) Or value.Length = 0) Then
Return False
Else
If _propertyToValidate.Equals("Zip") Then
If Regex.IsMatch(value, "(^(?!0{5})(\d{5})(?!-?0{4})(-?\d{4})?$)") = False Then
ErrorMessage = "Invalid Postal Code format,Please try xxxxx or xxxxx-xxxx"
Return False
Else
Return True
End If
End If
If _propertyToValidate.Equals("Phone") Then
If Regex.IsMatch(value, "((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}") = False Then
ErrorMessage = "Invalid Phone format,Please try (xxx)xxx-xxxx or xxx-xxx-xx"
Return False
Else
Return True
End If
End If
If _propertyToValidate.Equals("Email") Then
If Regex.IsMatch(value, "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*") = False Then
ErrorMessage = "Not a valid email"
Return False
Else
Return True
End If
End If
End If
End Function
Points of Interest
Coming from a background of backend business layer programming, the custom validators of ASP.NET2.0 saved my day.
History