In this article I will explain with an example, how to validate dd/MM/yyyy format date string in TextBox in ASP.Net using C# and VB.Net.
The dd/MM/yyyy date format string can be validated in the following possible ways
1. Using RegularExpressionValidator.
3. Using CustomValidator with Server Side validation using C# and VB.Net.
Regular Expression (Regex) to validate Date Format
Regular Expression (Regex)
(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$
This
Regular Expression (Regex) validates for months which have less than 31 days for example 15/06/2024 will be considered as a valid date.
1. Using RegularExpressionValidator
The HTML Markup consists of following controls:
TextBox – For capturing date.
Button – For submitting the Form.
RegularExpressionValidator – For validating the date.
The RegularExpressionValidator consists of following properties:
Properties
ClientValidationFunction – Name of the Client Side
JavaScript function
ValidationGroup – For specifying the group to which this validation control belongs.
ErrorMessage – For displaying error message when validation fails.
<asp:TextBox ID="txtDate1" runat="server" />
<asp:RegularExpressionValidator runat="server" ControlToValidate="txtDate1" ValidationExpression="(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$"
ErrorMessage="Invalid date format." ValidationGroup="Group1" />
<br /><br />
<asp:Button ID="Button1" Text="Validate" runat="server" ValidationGroup="Group1" />
2. Using CustomValidator and JavaScript
The HTML Markup consists of following controls:
TextBox – For capturing date.
Button – For submitting the Form.
CustomValidator – For validating the date.
The CustomValidator consists of following properties:
Properties
ClientValidationFunction – For executing in the user's browser to validate form date before it is sent to the server.
ControlToValidate – Sets the control ID to validate. Here ID of TextBox is set.
ValidationGroup – For specifying the group to which this validation control belongs.
ErrorMessage – For displaying error message when validation fails.
<asp:TextBox ID="txtDate2" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="ValidateDate" ControlToValidate="txtDate2"ErrorMessage="Invalid date format." ValidationGroup="Group2" />
<br /><br />
<asp:Button ID="Button2" Text="Validate" runat="server" ValidationGroup="Group2" />
Validating date string in dd/MM/yyyy format in ASP.Net
1. Whether the date string is in valid format i.e. dd/MM/yyyy.
2. If the above case is true then, it is verified whether it is a valid date.
Based on the validation the isValid property is set.
<script type="text/javascript">
function ValidateDate(sender, args) {
var dateString = document.getElementById(sender.controltovalidate).value;
var regex = /(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$/;
if (regex.test(dateString)) {
var parts = dateString.split("/");
var dt = new Date(parts[1] + "/" + parts[0] + "/" + parts[2]);
args.IsValid = (dt.getDate() == parts[0] && dt.getMonth() + 1 == parts[1] && dt.getFullYear() == parts[2]);
} else {
args.IsValid = false;
}
}
</script>
3. Using CustomValidator with Server Side validation
HTML Markup
The HTML Markup consists of following controls:
TextBox – For capturing date.
Button – For submitting the Form.
CustomValidator – For validating the date.
The CustomValidator has been assigned with an OnServerValidate event handler.
The CustomValidator consists of following properties:
Properties
ControlToValidate – Sets the control ID to validate. Here ID of TextBox is set.
ValidationGroup – For specifying the group to which this validation control belongs.
ErrorMessage – For displaying error message when validation fails.
<asp:TextBox ID="txtDate3" runat="server" />
<asp:CustomValidator ID="CustomValidator2" runat="server" OnServerValidate="ValidateDate"ControlToValidate="txtDate3" ErrorMessage="Invalid date format." ValidationGroup="Group3" />
<br /><br />
<asp:Button ID="Button3" Text="Validate" runat="server" ValidationGroup="Group3" />
Namespaces
You will need to import the following namespaces.
C#
using System.Globalization;
using System.Text.RegularExpressions;
VB.Net
Imports System.Globalization
Imports System.Text.RegularExpressions
Validating Date on Server side in ASP.Net
When the Validate button is clicked, the dd/MM/yyyy format validation and valid DateTime validation both are performed.
dd/MM/yyyy format validation
First a check is performed if the value of the
TextBox is in valid format i.e. dd/MM/yyyy using the
Regular Expression (Regex).
Valid DateTime validation
This validation checks whether the Date is a valid date and to check it, it is converted into a DateTime object.
If the Date is valid then, an appropriate message is displayed in
JavaScript Alert Message Box using
RegisterStartupScript method otherwise the validation fails.
C#
protected void ValidateDate(object sender, ServerValidateEventArgs e)
{
if(Regex.IsMatch(txtDate3.Text, "(((0|1)[0-9]|2[0-9]|3[0-1])\\/(0[1-9]|1[0-2])\\/((19|20)\\d\\d))$"))
{
DateTime dt;
e.IsValid = DateTime.TryParseExact(e.Value, "dd/MM/yyyy", new CultureInfo("en-GB"), DateTimeStyles.None, out dt);
if (e.IsValid)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Valid Date.');", true);
}
}
else
{
e.IsValid = false;
}
}
VB.Net
Protected Sub ValidateDate(sender As Object, e As ServerValidateEventArgs)
If Regex.IsMatch(txtDate3.Text, "(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$") Then
Dim dt As DateTime
e.IsValid = DateTime.TryParseExact(e.Value, "dd/MM/yyyy", New CultureInfo("en-GB"), DateTimeStyles.None, dt)
If e.IsValid Then
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Valid Date.');", True)
End If
Else
e.IsValid = False
End If
End Sub
Screenshot
Demo
Downloads