Click here to Skip to main content
15,896,512 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Dear Member,
i want to check validation on text box that text box allow only DD/MM/YYYY format in c sharp.i get many code but these code not working properly.

please post your code

thak you
member of code project
Posted
Comments
Sergey Alexandrovich Kryukov 7-Feb-12 21:57pm    
Totally incorrect question. What exactly type do you mean when you say "text box"? It could be WPF, Forms, Silverlight, ASP.NET. Tag it.

By the way, why text box?
--SA

1 solution

try this code

HTML
<asp:textbox runat="server" id="TextBox1" xmlns:asp="#unknown" />
<asp:customvalidator runat="server" controltovalidate="TextBox1" errormessage="Date was in incorrect format" onservervalidate="CustomValidator1_ServerValidate" xmlns:asp="#unknown" />


Code Behind
C#
protected void CustomValidator1_ServerValidate(object sender, ServerValidateEventArgs e)
{
    DateTime d;
    e.IsValid = DateTime.TryParseExact(e.Value, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out d);
}

/*If you want to allow other formats */

DateTime.TryParseExact(e.Value, new[] { "dd/MM/yyyy", "yyyy-MM-dd" }, CultureInfo.InvarinatCulture, DateTimeStyles.None, out d);




Other Solution----------
C#
public void Button1_Click(object sender, EventArgs e)
{
        DateTime Test;
        if (DateTime.TryParseExact(TextBox1.Text, "MM/dd/yyyy", null, DateTimeStyles.None, out Test) == true)
            Response.Write("Date is Valid");
        else
            Response.Write("Invalid Date");
}
 
Share this answer
 
Comments
zyck 7-Feb-12 9:38am    
please vote if it can help you
Member 14547345 24-Nov-19 4:40am    
thank u solved my problem

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900