[英]How to apply Custom Validation rules to ViewModel attribute in MVC3
在我的MVC應用程序中,我具有以下ViewModel
:
public class MyViewModel
{
public int StartYear { get; set; }
public int? StartMonth { get; set; }
public int? StartDay { get; set; }
public int? EndYear { get; set; }
public int? EndMonth { get; set; }
public int? EndDay { get; set; }
[DateStart]
public DateTime StartDate
{
get
{
return new DateTime(StartYear, StartMonth ?? 1, StartDay ?? 1);
}
}
[DateEnd(DateStartProperty="StartDate")]
public DateTime EndDate
{
get
{
return new DateTime(EndYear ?? DateTime.MaxValue.Year, EndMonth ?? 12, EndDay ?? 31);
}
}
}
我不使用日歷助手,因為我需要這種格式的日期(后面有邏輯)。 現在,我創建了自定義驗證規則:
public sealed class DateStartAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
DateTime dateStart = (DateTime)value;
return (dateStart > DateTime.Now);
}
}
public sealed class DateEndAttribute : ValidationAttribute
{
public string DateStartProperty { get; set; }
public override bool IsValid(object value)
{
// Get Value of the DateStart property
string dateStartString = HttpContext.Current.Request[DateStartProperty];
DateTime dateEnd = (DateTime)value;
DateTime dateStart = DateTime.Parse(dateStartString);
// Meeting start time must be before the end time
return dateStart < dateEnd;
}
}
問題是DateStartProperty
(在本例中為StartDate
)不在Request
對象中,因為它是在將表單發布到服務器后計算的。 因此, dateStartString
始終為null。 如何獲得StartDate
的值?
試試這個插件: http : //docs.jquery.com/Plugins/Validation/multiplefields 。
希望這會有所幫助〜
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.