tags:

views:

27

answers:

3

I have a simple validator that should check if the the date format is incorrect. I am doing testing and enter 2/14/201... which gets passed through my validator as 2/14/0201. How do I prevent this and jump to e.IsValid = false;?

protected void rangeVal(object sender, ServerValidateEventArgs e)
{
    DateTime dateCheck = txtDate1.Text.Trim();
    DateTime select;
    if (DateTime.TryParse(dateCheck, out select))
        e.IsValid = true;
    else
        e.IsValid = false;
}
A: 

You could check the string length of string coming in before turning it into a date time, you could split the string on the / and parse the year to make sure it is valid within your range, you could add a secondary conditional that checks the year before the TryParse.

Joel Etherton
+3  A: 

Should dateCheck be a string instead of a DateTime?

If only dates > the year 1900 are valid, you could try:

if (DateTime.TryParse(dateCheck, out select) && dateCheck > default(DateTime))
    e.IsValid = true;
else
    e.IsValid = false;

and that might suit your requirement.

Antony Koch
A: 

How is an unpadded year any less valid?

From MSDN DateTime structure:

The DateTime value type represents dates and times with values ranging from 12:00:00 midnight, January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.)

You should try something like this:

protected void rangeVal(object sender, ServerValidateEventArgs e)
{
    DateTime dateCheck = txtDate1.Text.Trim();
    DateTime select;
    if (DateTime.TryParse(dateCheck, out select))
    {
        e.IsValid = IsDateTimeValidForMyApplication(select);
    }
    else
        e.IsValid = false;
}

bool IsDateTimeValidForMyApplication(DateTime dt)
{
    return dt.Year > 2000;   //or whatever business rules your app has...
}
Austin Salonen