ASP.NET MVC 2中的动态范围验证

时间:2010-02-25 13:37:05

标签: asp.net-mvc validation

我正在使用ASP.NET MVC2并尝试使用System.ComponentModel.DataAnnotations命名空间中的属性验证我的视图模型。

如何动态设置RangeAttribute的允许有效范围? 例如,如果我想验证输入的日期是否在预期范围内。

这不编译:

[Range(typeof(DateTime), 
        DateTime.Today.ToShortDateString(), 
        DateTime.Today.AddYears(1).ToShortDateString())]
    public DateTime DeliveryDate { get; set; }

因为“属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式”。

我是否需要求助于创建自己的自定义验证器?

2 个答案:

答案 0 :(得分:15)

好的,找到了答案。 .NET Framework 4提供了一个新的CustomValidationAttribute,它使以下内容成为可能:

[Required]
[DisplayName("Ideal Delivery Date")]
[CustomValidation(typeof(HeaderViewModel), "ValidateDeliveryDate")]
public DateTime DeliveryDate { get; set; }

public static ValidationResult ValidateDeliveryDate(DateTime deliveryDateToValidate)
{
    if (deliveryDateToValidate.Date < DateTime.Today)
    {
    return new ValidationResult("Delivery Date cannot be in the past.");
    }

    if (deliveryDateToValidate.Date > DateTime.Today.AddYears(1))
    {
    return new ValidationResult("Delivery Date must be within the next year.");
    }

    return ValidationResult.Success;
}

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute%28VS.100%29.aspx

答案 1 :(得分:0)

您需要创建自己的属性或使用基于无属性的验证框架。正如消息所说,任何属性的所有参数都必须是常量值。