How to validate Date entries.

  • Thread starter Thread starter YardDancer
  • Start date Start date
Y

YardDancer

Hi All,

Does anybody have a routine for validating a date or DateTime entry in a
textbox.

I know i can use one of the DateTime.Parse(textbox.text) methods which
would throw a Fromat Exception.

What i am after is something like a IsNumeric() fuction or way i can test a
value if it is dateTime value and recieve a boolean answer i.e. true or
false.

Yard Dancer
Practicing at home before I attempt to dance at the hall.
 
Hi,

If you are using vb 2005 I would use DateTime.TryParse otherwise
I would use a regex.

http://msdn2.microsoft.com/en-us/library/system.datetime.tryparse.aspx

Dim dtnow As DateTime

If DateTime.TryParse("1/1/2006", dtnow) Then
Me.Text = dtnow.ToString
End If

Regex example

Dim dtNow As DateTime
Dim strDate As String = "1/1/2006"
Dim regDate As New
System.Text.RegularExpressions.Regex("^\d{1,2}\/\d{1,2}\/\d{4}$")
If regDate.IsMatch(strDate) Then
dtNow = Date.Parse(strDate)
Me.Text = dtNow.ToString
End If

http://www.regexlib.com/Search.aspx?k=date

Ken
 
It's tricky to write such a validation routine because "invalid date" is
quite relative.

For instance "13/1/2006" is a valid in some regions but not in others.

If you know the region you can do this:

string UK="13/1/2006";
DateTime UKDate = DateTime.Parse(UK,new System.Globalization.CultureInfo("en-gb"));

You could probably put this in a function and catch any format exceptions
and return false.
 
Hi Kerry,

I want to write all my routines using methods and properties that are
consistent
with the .Net Framework class library. I am trying to avoid using
functions
from the VB run-time library.
 
Back
Top