I am a new C# developer and I am using Regular Expression for my first time. As I am developing a validation class for my simple project, I am using Regex to develop a method validate the date entered by the user. The date should be of format MM/DD/YYYY only. I've developed the method but it gave me incorrect validation and I don't know why.
Here's the C# Regex method code:
public bool ValidateDate(string dateInput)
{
Regex datePattern = new Regex("^(1[0-2]|0[1-9])/(3[01]|[12][0-9]|0[1-9])/[0-9]{4}$");
return !datePattern.IsMatch(dateInput);
}
Then, since I have the following TextBox in ASP.NET:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
Code-Behind:
protected void Button1_Click(object sender, EventArgs e)
{
Validator validator = new Validator();
if (TextBox1.Text.ToString() != "")
{
if (validator.ValidateDate(TextBox1.Text.ToString()))
{
lblMessage.Text = "Correct";
}
else
{
lblMessage.Text = "Incorrect";
}
}
else
{
lblMessage.Text = "Please enter a text";
}
}
When I tried to use the validation method with this textbox, it gave me incorrect result. For example, when I entered 11/10/2013, it gave me Incorrect. However, when I entered 2013/11/10, it gave me Correct and I don't know why
Would you kindly help me in fixing/modifying this validation method?