mvc4 数据注释比较两个日期 [英] mvc4 data annotation compare two dates

查看:19
本文介绍了mvc4 数据注释比较两个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型中有这两个字段:

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; }

我要求 endDate 必须大于 startDate.我尝试使用 [Compare("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?

推荐答案

看一看 Fluent ValidationMVC Foolproof Validation:这些可以帮到你很多.

Take a look at Fluent Validation or MVC Foolproof Validation: those can help you a lot.

以 Foolproof 为例,有一个 [GreaterThan("StartDate")] 注释,您可以在日期属性上使用.

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(
               errorMessage: "EndDate must be greater than StartDate",
               memberNames: new[] { "EndDate" }
          );
       }
    }
}

这篇关于mvc4 数据注释比较两个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆