.NET MVC自定义日期验证 [英] .NET MVC Custom Date Validator
问题描述
我会处理编写自定义日期验证类的明天开会的应用程序我工作在工作中,将验证如果给定的开始或结束日期为A),比当前日期少,或B)启动日期大于本次会议的最后一天(反之亦然)。
我觉得这可能是一个相当普遍的要求。任何人都可以点我在一篇博客文章中的方向,可能会帮助我在解决这个问题?
我使用的是.NET 3.5,所以我不能使用内置于.NET 4的项目我的工作是MVC 2的新模式验证器API。
更新:课堂上,我正在写需要延长System.ComponentModel.DataAnnotations命名空间。在.NET 4中有一个IValidateObject接口,可以实现,这使得这样的事情绝对轻而易举,但遗憾的是我不能使用.NET 4我如何去这样做同样的事情在.NET 3.5中<? / P>
公共密封类DateStartAttribute:ValidationAttribute
{
公众覆盖布尔的IsValid(对象的值)
{
日期时间dateStart =(日期时间)值;
//会议必须开始在未来的时间。
返回(dateStart&GT; DateTime.Now);
}
}
公共密封类DateEndAttribute:ValidationAttribute
{
公共字符串DateStartProperty {获得;组; }
公众覆盖布尔的IsValid(对象的值)
{
//获取DateStart属性的值
字符串dateStartString = HttpContext.Current.Request [DateStartProperty]
日期时间dateEnd =(日期时间)值;
日期时间dateStart = DateTime.Parse(dateStartString);
//会议开始时间必须在结束时间之前
返回dateStart&LT; dateEnd;
}
}
和您的视图模型:
[DateStart]
公开日期时间起始日期{获得;组; }
[DateEnd(DateStartProperty =开始日期)]
公共DateTime的结束日期{获得;组; }
在你的行动,只是检查ModelState.IsValid。那你以后?
I'll be tackling writing a custom date validation class tomorrow for a meeting app i'm working on at work that will validate if a given start or end date is A) less than the current date, or B) the start date is greater than the end date of the meeting (or vice versa).
I think this is probably a fairly common requirement. Can anyone point me in the direction of a blog post that might help me out in tackling this problem?
I'm using .net 3.5 so i can't use the new model validator api built into .NET 4. THe project i'm working on is MVC 2.
UPDATE: THe class i'm writing needs to extend the System.ComponentModel.DataAnnotations namespace. In .NET 4 there is a IValidateObject interface that you can implement, that makes this sort of thing an absolute doddle, but sadly i can't use .Net 4. How do i go about doing the same thing in .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;
}
}
and in your View Model:
[DateStart]
public DateTime StartDate{ get; set; }
[DateEnd(DateStartProperty="StartDate")]
public DateTime EndDate{ get; set; }
In your action, just check that ModelState.IsValid. That what you're after?
这篇关于.NET MVC自定义日期验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!