动态范围验证在ASP.NET MVC 2 [英] Dynamic Range Validation in ASP.NET MVC 2
问题描述
我使用ASP.NET MVC2,并尝试使用该属性在System.ComponentModel.DataAnnotations命名空间我的视图模型来验证。
I am using ASP.NET MVC2 and trying to validate my view models using the attributes in System.ComponentModel.DataAnnotations namespace.
我如何动态地设置RangeAttribute所允许的有效范围?
例如,如果我想验证输入的日期是可预期的范围内。
How can I dynamically set the permitted valid range of a RangeAttribute? For example, if I want to validate that a date entered is within an expected range.
这不会编译:
[Range(typeof(DateTime),
DateTime.Today.ToShortDateString(),
DateTime.Today.AddYears(1).ToShortDateString())]
public DateTime DeliveryDate { get; set; }
由于属性参数必须是常量前pression,属性参数类型的typeof前pression或数组创建前pression。
because "an attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type".
我是否需要借助于创建自己的自定义验证?
Do I need to resort to creating my own custom validator?
推荐答案
OK,找到了答案。 .NET框架4提供了一个新的CustomValidationAttribute这使得以下可能:
OK, found the answer. .NET Framework 4 provides a new CustomValidationAttribute which makes the following possible:
[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;
}
<一个href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute%28VS.100%29.aspx\">http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute%28VS.100%29.aspx
这篇关于动态范围验证在ASP.NET MVC 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!