mvc4数据注解比较两个日期 [英] mvc4 data annotation compare two dates
问题描述
我在我的模型这两个领域:
I have these two fields in my model:
[Required(ErrorMessage="The start date is required")]
[Display(Name="Start Date")]
[DisplayFormat(DataFormatString = "{0,d}")]
public DateTime startDate { get; set; }
[Required(ErrorMessage="The end date is required")]
[Display(Name="End Date")]
[DisplayFormat(DataFormatString = "{0,d}")]
public DateTime endDate{ get; set; }
我要求结束日期
必须比的startDate
更大。我试着用 [比较(的startDate)]
但这只是作品的平等操作。
I require that endDate
must be greater than startDate
. I tried using [Compare("startDate")]
but this only works for the equal operation.
我应该怎么使用的操作大于?
What should I use for the "greater than" operation?
推荐答案
看看流利的验证或<一个HREF =HTTP://foolproof.$c$cplex.com/> MVC万全验证:在那些可以帮助你很多。
Take a look at Fluent Validation or MVC Foolproof Validation: those can help you a lot.
通过万全例如有一个 [GREATERTHAN(起始日期)]
注释比你可以在你的日期属性使用。
With Foolproof for example there is a [GreaterThan("StartDate")]
annotation than you can use on your date property.
或者,如果你不想用到其他库,可以通过实施 IValidatableObject
在你的模型实现自己的自定义验证
Or if you don't want to use other libraries, you can implement your own custom validation by implementing IValidatableObject
on your model:
public class ViewModel: IValidatableObject
{
[Required]
public DateTime StartDate { get; set; }
[Required]
public DateTime EndDate { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (EndDate < StartDate)
{
yield return new ValidationResult("EndDate must be greater than StartDate");
}
}
}
这篇关于mvc4数据注解比较两个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!