开发者

DataAnnotations on a DateTime property

I have a DateTime property in my model and I would like to validate it using DataAnnotations.

In my view I want to get that DateTime as a number of days (e.g. "3"), instead of a DateTime (e.g. "7/14/2010"). If user enters "3" in the view, then DataAnnotation finds it invalid -and that is the issue.

What are my options in this scenario?

Thank开发者_JAVA百科 you very much for your help.


It sounds like you are using the wrong type for the job. A measurement in "days" is a TimeSpan, not a DateTime. I would update your model to expose the property as a TimeSpan. You could validate with a custom validator like the following:

[AttributeUsage(AttributeTargets.Property|AttributeTargets.Field, AllowMultiple = false)]
public class TimeSpanAttribute: ValidationAttribute
{
    public override bool IsValid(object value)
    {
        if (value is TimeSpan)
        {
            return true;
        }
        else if (value is String)
        {
            TimeSpan result;
            return TimeSpan.TryParse((string)value, out result);
        }

        return false;
    }
}


I think you're comparing apples with oranges. If you specified that your property is DateTime you can't enter the value 3 for that property.

Why not make this property of type Int?

Afterwards, if you need to return a DateTime... just use this Integer value to create whatever date you need adding or subtracting for example:

DateTime myDate = DateTime.Now.Date.AddDays(intValue);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜