Кто-нибудь видел аннотацию данных MVC3 для проверки даты, которая требует, чтобы одна выбранная дата была равна или больше текущей даты?
Если уже есть стороннее дополнение, это тоже круто. Я уже использую DataAnnotationsExtensions, но он не предлагает то, что я ищу.
Кажется, нет никаких упоминаний об этом. Итак, надеюсь, что кто-то уже решил эту проблему, прежде чем я попытаюсь изобрести велосипед и написать свой собственный валидатор.
Я пробовал Range
, но для этого требуется 2 даты, и обе должны быть константами в строковом формате, например [Range(typeof(DateTime), "1/1/2011", " 01.01.2016")]
, но это не помогает. А валидатор DataAnnotationsExtensions Min
принимает только int
и double
UpdateРешено
Благодаря @BuildStarted это то, что у меня получилось, и это работает отлично работает на стороне сервера, а теперь и на стороне клиента с моим скриптом
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace Web.Models.Validation {
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class DateMustBeEqualOrGreaterThanCurrentDateValidation : ValidationAttribute, IClientValidatable {
private const string DefaultErrorMessage = "Date selected {0} must be on or after today";
public DateMustBeEqualOrGreaterThanCurrentDateValidation()
: base(DefaultErrorMessage) {
}
public override string FormatErrorMessage(string name) {
return string.Format(DefaultErrorMessage, name);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
var dateEntered = (DateTime)value;
if (dateEntered < DateTime.Today) {
var message = FormatErrorMessage(dateEntered.ToShortDateString());
return new ValidationResult(message);
}
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
var rule = new ModelClientCustomDateValidationRule(FormatErrorMessage(metadata.DisplayName));
yield return rule;
}
}
public sealed class ModelClientCustomDateValidationRule : ModelClientValidationRule {
public ModelClientCustomDateValidationRule(string errorMessage) {
ErrorMessage = errorMessage;
ValidationType = "datemustbeequalorgreaterthancurrentdate";
}
}
}
И в моей модели
[Required]
[DateMustBeEqualOrGreaterThanCurrentDate]
public DateTime SomeDate { get; set; }
Скрипт на стороне клиента
/// <reference path="jquery-1.7.2.js" />
jQuery.validator.addMethod("datemustbeequalorgreaterthancurrentdate", function (value, element, param) {
var someDate = $("#SomeDate").val();
var today;
var currentDate = new Date();
var year = currentDate.getYear();
var month = currentDate.getMonth() + 1; // added +1 because javascript counts month from 0
var day = currentDate.getDate();
var hours = currentDate.getHours();
var minutes = currentDate.getMinutes();
var seconds = currentDate.getSeconds();
today = month + '/' + day + '/' + year + ' ' + hours + '.' + minutes + '.' + seconds;
if (someDate < today) {
return false;
}
return true;
});
jQuery.validator.unobtrusive.adapters.addBool("datemustbeequalorgreaterthancurrentdate");