How to Write a Custom Date Validator
This article describes how to write a custom date validator by inheriting
from CustomValidator.
The Custom Date Validator Code
First, here's the class code:
Imports Microsoft.VisualBasic
Namespace Planets
Public Class DateValidator
Inherits System.Web.UI.WebControls.CustomValidator
Public Sub DateValidate(ByVal sender As Object, ByVal Args As ServerValidateEventArgs)
Dim DateIn As String
Dim DateOut As DateTime
DateIn = CType(Args.Value, String)
Args.IsValid = DateTime.TryParse(DateIn, DateOut)
End Sub
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
Display = ValidatorDisplay.Dynamic
ErrorMessage = "<br>Invalid date"
AddHandler ServerValidate, AddressOf DateValidate
MyBase.OnLoad(e)
End Sub
End Class
End Namespace
OnLoad
When our custom date validator is loaded into the web page we want to
set a few default values for the control.
We set these default values by overriding the OnLoad event and perform these actions:
- Set the default Display mode. I like Dynamic mode.
- Set the default ErrorMessage. I place error messages under the control using the BR tag.
- Add an event handler for the ServerValidate event.
- Call the base class OnLoad event method.
DateValidate
When the user clicks on a form submit button the ASP.NET framework will call the ServerValidate event,
in our case, DateValidate, to validate the data entered or selected by the user.
The event takes the ServerValidateEventArgs argument which has two key properties:
- Value - Contains the value we need to validate
- IsValid - Indicates whether Value is valid.
In the DateValidate event we:
- Convert the value into a string data type.
- Attempt to parse the string using the DateTime.TryParse.
TryParse() attempts to parse the string and returns a boolean value
instead of throwing an exception.
- Set the IsValid property on the ServerValidateEventArgs object with the boolean status
returned by TryParse().
Using the Custom Validator
Add a Register tag into the beginning of your ASPX page:
<%@ Register Namespace="Planets" TagPrefix="Planets"%>
Add the DateValidator to your ASPX page below the field you are checking:
<asp:TextBox ID="Birthdate" runat="server">
<Planets:DateValidator ControlToValidate="Birthdate" runat="server">
</Planets:DateValidator>
Set the custom validator ControlToValidate value to the ID of the TextBox.
* You can place validator controls any where in your ASPX file. I find it
easier to understand the code when you place validator controls near the
field you are validating.
Summary
We can use our new custom date validator anywhere in our project when
we need to validate a date without having to write new validation code.
This ability to use the same control in multiple places saves us development time and costs.
|