【问题标题】:Dynamic Range Validation in ASP.NET MVC 2ASP.NET MVC 2 中的动态范围验证
【发布时间】:2010-02-25 13:37:04
【问题描述】:

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

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

这不会编译:

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

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

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

【问题讨论】:

    标签: asp.net-mvc validation


    【解决方案1】:

    好的,找到答案了。 .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

    【讨论】:

    • 无论如何要验证我是否有两个日期类型属性,如开始日期和结束日期,并使用这样的某种方案(自定义验证类、属性)确保开始不在结束之后?
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-06
      • 1970-01-01
      • 1970-01-01
      • 2013-11-29
      • 1970-01-01
      相关资源
      最近更新 更多