MrB*_*liz 12 .net c# asp.net-mvc data-annotations asp.net-mvc-2
我将在明天为我正在工作的会议应用程序编写一个自定义日期验证课程,该会议应用程序将验证给定的开始或结束日期是否小于当前日期,或者B)开始日期更长比会议结束日期(反之亦然).
我认为这可能是一个相当普遍的要求.任何人都可以指向我的博客文章的方向,可能会帮助我解决这个问题?
我正在使用.net 3.5所以我不能使用.NET 4中内置的新模型验证器api.我正在研究的项目是MVC 2.
更新:我正在编写的类需要扩展System.ComponentModel.DataAnnotations命名空间.在.NET 4中有一个你可以实现的IValidateObject接口,这使得这种事情变得绝对轻而易举,但遗憾的是我不能使用.Net 4.我如何在.Net 3.5中做同样的事情?
jus*_*mmy 22
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;
}
}
Run Code Online (Sandbox Code Playgroud)
并在您的视图模型中:
[DateStart]
public DateTime StartDate{ get; set; }
[DateEnd(DateStartProperty="StartDate")]
public DateTime EndDate{ get; set; }
Run Code Online (Sandbox Code Playgroud)
在您的操作中,只需检查ModelState.IsValid.那你在追求什么?
| 归档时间: |
|
| 查看次数: |
13606 次 |
| 最近记录: |