mvc-model日期范围注释动态日期

时间:2015-03-03 07:59:18

标签: c# asp.net-mvc validation date

参考stackoverflow

中的这个帖子
[Range(typeof(DateTime), "1/2/2004", "3/4/2004",
    ErrorMessage = "Value for {0} must be between {1} and {2}")]
public DateTime EventOccurDate{get;set;}

我尝试将一些动态日期添加到我的模型的日期范围验证器中:

private string currdate=DateTime.Now.ToString();
private string futuredate=DateTime.Now.AddMonths(6).ToString();

[Range(typeof(DateTime),currdate,futuredate,
    ErrorMessage = "Value for {0} must be between {1} and {2}")]
public DateTime EventOccurDate{get;set;}

但是发生了错误。有没有办法在MVC中设置动态日期范围验证?

1 个答案:

答案 0 :(得分:3)

您不能在属性中使用动态值,因为它们是在编译时生成的元数据。实现此目的的一种可能性是编写自定义验证属性或使用Fluent Validation,这允许使用流畅的表达式表达更复杂的验证方案。

以下是此类自定义验证属性的示例:

public class MyValidationAttribute: ValidationAttribute
{
    public MyValidationAttribute(int monthsSpan)
    {
        this.MonthsSpan = monthsSpan;
    }

    public int MonthsSpan { get; private set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            var date = (DateTime)value;
            var now = DateTime.Now;
            var futureDate = now.AddMonths(this.MonthsSpan);

            if (now <= date && date < futureDate)
            {
                return null;
            }
        }

        return new ValidationResult(this.FormatErrorMessage(this.ErrorMessage));
    }
}

然后用它装饰你的模型:

[MyValidation(6)]
public DateTime EventOccurDate { get; set; }