Easy Date Validation in Visual Basic

Introduction

This article describes a simple approach to validating dates received as strings (e.g., 2/21/2008). It requires on a few lines of code but will confirm that the date provided as a string is an actual date. The formats for the date string used in this example conform to the US standard of MM/DD/YYYY but that can easily be modified to work with other UI cultures. The method shown may be of use if you have an application that receives dates as strings rather than as actual DateTime values.

Date-Validator-in-VB.NET.gif

Figure 1: Test Application in Use

The Code

The code is very simple and does not require much of an explanation. All that is done is to split the date string up into month, day, and year, and then to attempt to create a date time value from those parts. If the operation succeeds, the method returns true, if it fails (with an invalid date) the failure is trapped in a catch block which in turn returns a false. The sum total of the operation is as follows:

     ''' <summary>
    ''' Determine if Date String is an actual date
    ''' Date format = MM/DD/YYYY
    ''' </summary>
    ''' <param name="dateString"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ValidateDate(ByVal dateString As StringAs Boolean

        Try
            ' for US, alter to suit if splitting on hyphen, comma, etc.
            Dim dateParts() As String = dateString.Split("/")

            ' create new date from the parts; if this does not fail
            ' the method will return true
            Dim testDate As New Date(Convert.ToInt32(dateParts(2)), _
                                     Convert.ToInt32(dateParts(0)), _
                                     Convert.ToInt32(dateParts(1)))

             Return True

         Catch ex As Exception

            ' if a test date cannot be created, the
            ' method will return false
            Return False

         End Try

     End Function


Similar Articles