Regular expression for validating Date in vb.net

Regular expressions are a good way to validate text fields such as date, names, addresses, phone numbers, and other user information. You can use the System.Text.RegularExpressions.Regex class for validate any input string for any specific format.

The following example will allow you to Input valid date format only

Private Sub ValidateDate(ByVal txtDate As String)
     If Not Regex.IsMatch(txtDate, _
    "^\s*\d{1,2}(/|-)\d{1,2}\1(\d{4}|\d{2})\s*$") Then
        MessageBox.Show("valid date")
    Else
        MessageBox.Show("invalid date")
    End If
End Sub

[Code Explanation]

The following pattern checks whether the input string is a date in the format mm-dd-yy or mm-dd-yyyy. Key pattern elements used are:

\d{1,2}Month and day numbers can have 1 or 2 digits. The use of (\d{4}|\d{2}) means the year can have 2 or 4 digits
(/|-)Either the slash or the dash are valid date separators
\1The separator used for the day and year must be the same as the separator used for month and day. The 1 refers to the first numbered group, defined by parentheses, e.g, (/|-).

 

Note: we could improve on this pattern by ensuring that digits do not start with a zero and that they are in a valid numerical range.

More on Regular Expressions