Home »
.NET 4.0 »
Validate date in code behind with regex – VB.NET
Validate date in code behind with regex – VB.NET
Code behind
'define public var
Protected StartDate As String
Protected EndDate As String
'define other var
Dim sDate = Request.Form("startDateTbx")
Dim eDate = Request.Form("endDateTbx")
Dim r As Regex
r = New Regex("^(0[1-9]|[1-9]|1[012])/(0[1-9]|[1-9]|[12][0-9]|3[01])/20\d\d$")
'run validation
If sDate = "" Then
startDateLbl.Text = "Required"
ElseIf Not r.Match(sDate).Success Then
startDateLbl.Text = "Invalid date. Use mm/dd/yyyy."
Else
startDateLbl.Text = ""
End If
If eDate <> "" And Not r.Match(eDate).Success Then
endDateLbl.Text = "Invalid date. Use mm/dd/yyyy."
Else
endDateLbl.Text = ""
End If
StartDate = sDate
EndDate = eDate
Markup page
<%=StartDate%>
<%=EndDate%>
Tags: ASP.NET, Controls, Form Validation, Visual Studio