.NET MVC自定义日期validation器

我将在明天为我正在开展工作的会议应用程序编写一个自定义日期validation课程,该工作将validation给定的开始或结束日期是否小于当前日期,或者B)开始日期更长比会议结束日期(反之亦然)。

我认为这可能是一个相当普遍的要求。 任何人都可以指向我的博客文章的方向,可能会帮助我解决这个问题?

我正在使用.net 3.5,所以我无法使用.NET 4中内置的新模型validation器api。我正在研究的项目是MVC 2。

更新:我正在编写的类需要扩展System.ComponentModel.DataAnnotations命名空间。 在.NET 4中,有一个可以实现的IValidateObject接口,这使得这种事情变得绝对轻而易举,但遗憾的是我不能使用.Net 4.我如何在.Net 3.5中做同样的事情?

public sealed class DateStartAttribute : ValidationAttribute { public override bool IsValid(object value) { DateTime dateStart = (DateTime)value; // Meeting must start in the future time. 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; } } 

并在您的视图模型中:

 [DateStart] public DateTime StartDate{ get; set; } [DateEnd(DateStartProperty="StartDate")] public DateTime EndDate{ get; set; } 

在您的操作中,只需检查ModelState.IsValid。 那你在追求什么?

我知道这篇文章比较老,但是,我发现这个解决方案要好得多。

如果对象在视图模型中具有前缀,则此post中接受的解决方案将不起作用。

即线条

 // Get Value of the DateStart property string dateStartString = HttpContext.Current.Request[DateStartProperty]; 

可在此处找到更好的解决方案: http : //www.a2zdotnet.com/View.aspx?Id = 182

我认为应该这样做:

 public boolean MeetingIsValid( DateTime start, DateTime end ) { if( start < DateTime.Now || end < DateTime.Now ) return false; return start > end || end < start; }