我将视图模型用于开始和结束日期,并使用数据注释进行验证。验证规则是:
- 开始日期不应大于结束日期且不为空,空白
- 结束日期不应小于开始日期且不小于 DateTime.Now 且不为空、空白
以下视图模型由 startdate 和 enddate 属性组成。令人困惑的是,如何在下面的代码中传递 StartEndDateRange 数据注释中的 EndDate 值和 EndDate 数据注释中的 StartDate 值:
public class StartEndDate
{
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[StartEndDateRange("2000/01/01", "value of end date properties")]
public DateTime StartDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[StartEndDateRange("value of startdate properties", DateTime.Now.ToString("yyyy/MM/dd"))]
public DateTime EndDate { get; set; }
}
public class StartEndDateRangeAttribute : ValidationAttribute
{
private const string DateFormat = "yyyy/MM/dd";
private const string DefaultErrorMessage =
"'{0}' must be a date between {1:d} and {2:d}.";
public DateTime MinDate { get; set; }
public DateTime MaxDate { get; set; }
public StartEndDateRangeAttribute(string minDate, string maxDate)
: base(DefaultErrorMessage)
{
MinDate = ParseDate(minDate);
MaxDate = ParseDate(maxDate);
}
public override bool IsValid(object value)
{
if (value == null || !(value is DateTime))
{
return true;
}
DateTime dateValue = (DateTime)value;
return MinDate <= dateValue && dateValue <= MaxDate;
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentCulture,
ErrorMessageString,
name, MinDate, MaxDate);
}
private static DateTime ParseDate(string dateValue)
{
return DateTime.ParseExact(dateValue, DateFormat,
CultureInfo.InvariantCulture);
}
}