Introduction
Have you ever come across the hassle of having a number of textboxes on your UI, and an associated Regex Validator with each textbox?
The custom textbox described below eliminates the use of adding validators for each and every textbox. Just by setting a couple of properties, we can make our textbox validate credit card numbers, phone numbers, etc. If this is not enough, then the textbox provides a property to set your own custom validation. We can also specify whether a field is mandatory or not.
The textbox has inbuilt support for validation of:
Email
- e.g. viv_cash@yahoo.com
PhoneNumber
- e.g. xxx-xxx-xxxx
URL
- e.g. http://www.google.com
CreditCard
- It should be a 16 digit number
MonthYear
- e.g. 08/2008
MonthDayYear
- e.g. 12/06/2006
Time
- e.g. 8:00 am, 12:20 pm
CustomExpression
- Any other expression as per requirement
Background
There have been instances in my project when there are a number of textboxes on my form's UI and I need to put a custom validator for each. Then the idea of a textbox with standard/custom validations came to my mind. It eliminates the use of adding validators for each and every textbox added. The custom control is particularly useful when we have a number of textboxes on the UI and we need to have a validator for each. It's quick, saves time and is hassle free.
Using the Code
The code has a single class CustTextBox
.The procedures and properties are explained below.
The ValidateValue
enumeration defines all the items that are supported by the custom textbox and can be validated. Each and every item has an associated regular expression with it.
If some item is to be validated which is not included in the list, assign CustomExpression
to the ValidateItem
property. Then set ExpressionValue
property to the regex (as string
) which will validate the value in the textbox.
Public Enum ValidateValue
Email
PhoneNumber
URL
CreditCard
MonthYear
MonthDayYear
Time
CustomExpression
End Enum
ValidateItem
property is of type ValidateValue
(enum
) and sets/returns a value indicating the item selected for validation.
IsRequired
property is of type boolean and sets/returns a value indicating whether it is a mandatory field or not.
ExpressionValue
property is of type string
and sets/returns a value that is used for validating the value in the textbox if CustomExpression
is used as ValidateItem
. If ValidateItem
is used as CustomExpression
, then this property needs to be set mandatorily.
Public Property ValidateItem() As ValidateValue
Get
Return _ValidateItem
End Get
Set(ByVal value As ValidateValue)
_ValidateItem = value
End Set
End Property
Public Property IsRequired() As Boolean
Get
Return _IsRequired
End Get
Set(ByVal value As Boolean)
_IsRequired = value
End Set
End Property
Public Property ExpressionValue() As String
Get
Return _ExpressionValue
End Get
Set(ByVal value As String)
_ExpressionValue = value
End Set
End Property
In the oninit
function, i.e. when the controls are initialized, attributes are added to the onblur
event of all the custom textboxes on UI. Depending on the type of ValidateItem
selected, a regex is assigned to the strRegExp
variable.
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
Dim strRegExp As String = ""
Select Case ValidateItem
Case ValidateValue.Email
strRegExp = "^([\\w\\-\\.]+)@((%22file://[([0-9]%7b1,3%7d//%22">\\[([0-9]{1,3}\\.)_
{3}[0-9]{1,3}\\])|(([\\w\\-]+\\.)+)([a-zA-Z]{2,4}))$"
Case ValidateValue.URL
strRegExp = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?"
Case ValidateValue.PhoneNumber
strRegExp = "((\\(\\d{3}\\) ?)|(\\d{3}-))?\\d{3}-\\d{4}"
Case ValidateValue.CreditCard
strRegExp = "^(\\d{4}[- ]){3}\\d{4}|\\d{16}$"
Case ValidateValue.MonthYear
strRegExp = "(((0[123456789]|10|11|12)([/])(([1][9][0-9][0-9])_
|([2][0-9][0-9][0-9]))))"
Case ValidateValue.MonthDayYear
strRegExp = "^(([1-9])|(0[1-9])|(1[0-2]))\\/(([0-9])|_
([0-2][0-9])|(3[0-1]))\\/(([0-9][0-9])|([1-2][0,9][0-9][0-9]))$"
Case ValidateValue.Time
strRegExp = "^ *(1[0-2]|[1-9]):[0-5][0-9] *(a|p|A|P)(m|M) *$"
Case ValidateValue.CustomExpression
strRegExp = ExpressionValue
End Select
Me.Attributes.Add("onblur", "Check('" + strRegExp + "',this,'" + _
IsRequired.ToString + "')")
MyBase.OnInit(e)
End Sub
Render
function used renders JavaScript to an ASP.NET textbox control output stream.
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
Dim strScript As String = "<script></script> "
writer.WriteLine(strScript)
MyBase.Render(writer)
End Sub
The heart of this custom control is the JavaScript that does all the tasks of validation. The JavaScript function Check()
accepts three parameters:
- The control that has fired the event
- The regular expression associated with that textbox. The regular expression could be that of a
CreditCard
, Time
, URL
or a custom regex.
- Boolean variable that indicates whether the field is required or not.
The JavaScript first checks whether the field is required or not. If it is required, then it checks whether the textbox contains a value or not. If it does not contain a value, a pop up message is shown. If a value exists, it is checked for validity. Depending on whether the field is valid
or invalid
, a pop up message is shown.
If the field is not required and no value is entered in the textbox, no action is taken. But if a value is entered, then it is checked for validity.
function Check(regex,obj,reqd)
{
re = new RegExp(regex);
var Prefix=obj.id;
var Ctrl=document.getElementById(Prefix);
var value=Ctrl.value;
if (reqd=='True')
{
if (value=='')
{
alert('Value Required');
Ctrl.focus();
}
else
{
if (re.test(value))
{
alert('Valid');
}
else
{
alert('InValid');
Ctrl.focus();
}
}
}
else
{
if (value=='')
{}
else
{
if (re.test(value))
{
alert('Valid');
}
else
{
alert('InValid');
Ctrl.focus();
}
}
}
}
History
- 4th June, 2008: Initial post