Asp.net-Mvc
mvc4數據註釋比較兩個日期
我的模型中有這兩個欄位:
[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")],但這僅適用於相等的操作。我應該為“大於”操作使用什麼?
看看Fluent Validation或MVC Foolproof Validation:這些對你有很大幫助。
以 Foolproof 為例,
[GreaterThan("StartDate")]您可以在 date 屬性上使用一個註釋。或者,如果您不想使用其他庫,您可以通過
IValidatableObject在模型上實現來實現自己的自定義驗證: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" } ); } } }