tags:

views:

17

answers:

2

Hi -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 you very much for your help.

+1  A: 

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);
Leniel Macaferi
Hi Leniel thank you for your help. I am afraid my question was not very clear, so I added a comment to my original post. Thank you again.
Bruno Ligutti
+1  A: 

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