简体   繁体   中英

validate date in an ASP.NET MVC application

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?

"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");

您需要MMmmMM是月,而mm为分钟。

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM