0

I want to check my date input value on server side.

Code:

public class DateAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        DateTime date;
        string str = value.ToString();

        if (!DateTime.TryParseExact(str, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
            return false;

        return true;
    }
}

but it always FALSE for object values like 21.11.2011 0:00:00

I can't to understand what I am doing wrong?

0

3 Answers 3

1

"mm" is a 2-digit minute. "MM" is a 2-digit month

If you want July to parse from "07", use "MM". On the other hand, if you want to parse "7" to July, use "M". Here's the huge list of formats.

EDIT: Using DateTime.TryParseExact to parse with a format string:

string dateString = "21.12.1985 3:12:15";
DateTime date;
if (DateTime.TryParseExact(dateString,"d.M.yyyy h:mm:ss",null,DateTimeStyles.None, out date))
    Console.WriteLine(date);
    else
        Console.WriteLine("Invalid date");
Sign up to request clarification or add additional context in comments.

3 Comments

You need MM not mm, MM is month while mm is minute. Thanks, you are right, but dd.MM.yyyy doesn't work too (
You need to use TryParseExact
Okay, modified my answer.
0

You need MM not mm, MM is month while mm is minute.

3 Comments

You need MM not mm, MM is month while mm is minute. Thanks, you are right, but dd.MM.yyyy doesn't work too (
It's possible the time part is messing it up. Try yyyy.MM.dd hh:mm:ss ?
@YuriyMayorov: I removed the time element and your code returned true. With the time, I get false. ???
0

I would wrap it around a try-catch statement and try to use Parse method on it. Since your current code doesn't actually return a particular formatted string, just whether it's valid or not I would do the following below. DateTime are just long ticks away from a particular date/time, so the format doesn't matter. From http://msdn.microsoft.com/en-us/library/1k1skd40.aspx we can see that there are only two-exceptions it'll throw, so just take these two exceptions into account and you can add code accordingly.

public override bool IsValid(object value)
{
    if (value != null)
    {
        try
        {
            DateTime date = DateTime.Parse(value.ToString());
            return true;
        }
        catch (ArgumentNullException)
        {
            // value is null so not a valid string
        }
        catch (FormatException)
        {
            //not a valid string
        }
    }
    return false;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.