tags:

views:

95

answers:

3

Using C#

C# Code

protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
    if(e.Value.Length == 8)
        e.IsValid = true;
    else
        e.IsValid = false;
}

Page code

<asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtoedate" onservervalidate="cusCustom_ServerValidate" errormessage="The text must be exactly 8 characters long!" />

The above code is working for the length, but i want to check the date format like this "yyyy-mm-dd", for checking this date format, how to change my code.

Need Code Help

+2  A: 

Well, firstly, your date format isn't 8 characters long, so you'll need to fix that to 10. Then your best bet is a DateTime.TryParseExact with the specific format you want to validate.

DateTime value;
e.IsValid = DateTime.TryParseExact(e.Value, "yyyy-MM-dd",
    CultureInfo.InvariantCulture, DateTimeStyles.None, out value);

You can get away with InvariantCulture because you are only dealing with the numeric representations of the date parts and are specifying the format exactly.

David M
Oh no, please don't do `try...catch` for validating dates. Use `DateTime.TryParseExact`.
Darin Dimitrov
Can i get a sample code
Gopal
@Darin - how did I know about `TryParse` but not `TryParseExact`? Thanks.
David M
@Gopal - in the answer (in case you didn't notice already...)
David M
A: 

Use the DateTime.TryParse Method .

Jaroslav Jandek
Can you provide sample code....
Gopal
A sample was in the link I provided, I guess it was not visible enough, sorry.
Jaroslav Jandek
A: 

try regular expression for date

Neo