OdeToCode IC Logo

What's Wrong With This Code (#27)

Monday, February 21, 2011

Cory Ander wanted to make sure his users enter a date value that is reasonably close to the current date. He's writing an MVC 3 app and envisioned using a validation attribute like the following.

public class TransactionDispute
{        
    [RecentDate]
    public DateTime TransactionDate { get; set; }

    // ...
}

Corey came up with the following.

public class RecentDateAttribute : ValidationAttribute
{
    public RecentDateAttribute()
        :base("{0} must be recent")
    {
        MinimumDate = DateTime.Now.AddDays(-1);            
    }

    protected DateTime MinimumDate { get; set; }

    protected override ValidationResult IsValid(
        object value, ValidationContext validationContext)
    {
        var date = (DateTime) value;
        if (date < MinimumDate)
        {
            return new ValidationResult(
                FormatErrorMessage(validationContext.DisplayName)
            );
        }
        return ValidationResult.Success;
    }
}

 

It seems to work - what could possibly be wrong?