Jagz S
Jagz S

Reputation: 907

Data Annotations Range validator for date

I am using Range Validator to validate the date. My requirement is validate the input date should be between current date and current date -60 years.

This is what I tried so far,

[Range(typeof(DateTime),DateTime.UtcNow.ToString(),DateTime.UtcNow.AddYears(-60).Date.ToString())]
public DateTime? DOJ { get; set; }

But this throws error : An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.

So I modified my code:

 #region variables
 public const string MaxDate = DateTime.UtcNow.ToString();
 public const string MinDate = DateTime.UtcNow.AddYears(-60).Date.ToString();
 #endregion

And Set property :

[Range(typeof(DateTime),maximum:MaxDate,minimum:MinDate)]
public DateTime? DOJ { get; set; }

Now the error is :The expression being assigned to 'MaxDate' must be constant.

Same for MinDate.

What's the solution?

Upvotes: 2

Views: 4139

Answers (1)

Sergey Litvinov
Sergey Litvinov

Reputation: 7458

You can't use variables in Attributes. All items in attributes must be constant. If you want to filter value based on dynamic values, then you can make new ValidationAttribute like this:

public class ValidateYearsAttribute : ValidationAttribute
{
    private readonly DateTime _minValue = DateTime.UtcNow.AddYears(-60);
    private readonly DateTime _maxValue = DateTime.UtcNow;

    public override bool IsValid(object value)
    {
        DateTime val = (DateTime)value;
        return val >= _minValue && val <= _maxValue;
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessage, _minValue, _maxValue);
    }
}

And then you just need to place it on your property:

 [ValidateYears]
 public DateTime? DOJ { get; set; }

You can update FormatErrorMessage based on what you need.

Upvotes: 2

Related Questions