В моем проекте есть senario, в котором мне нужно сравнить даты, чтобы определить, больше ли дата начала, чем дата окончания.Так что пока MVC3 не предоставляет свой собственный атрибут для сравнения дат.поэтому для этой цели я создал свой собственный атрибут для сравнения дат, который указан ниже
namespace WebUtil.Validators {using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;использование System.Web.Mvc;using WebUtil.Resources;
public class CompareDateAttribute : ValidationAttribute, IClientValidatable
{
public CompareDateAttribute(string otherPropertyName)
: base(WebUtilResources.Validation_Invalid_Dates)
{
this.OtherControlName = otherPropertyName;
}
public string OtherControlName { get; set; }
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name, this.OtherControlName);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
ModelMetadata metadata, ControllerContext context)
{
var greaterRule = new ModelClientValidationRule();
greaterRule.ErrorMessage = this.FormatErrorMessage(metadata.GetDisplayName());
greaterRule.ValidationType = "greater";
greaterRule.ValidationParameters.Add("other", this.OtherControlName);
yield return greaterRule;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var otherPropertyInfo = validationContext.ObjectType.GetProperty(this.OtherControlName);
var otherDate = (DateTime)otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
var thisDate = (DateTime)value;
if (thisDate <= otherDate)
{
var message = this.FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(message);
}
return null;
}
}
}
После создания этого атрибута для выполнения этой проверки на стороне клиента я добавил метод для ненавязчивого валидатора JQuery, подобный этому.
jQuery.validator.addMethod("greater", function (value, element, param) {
return Date.parse(value) > Date.parse($(param).val());
});
jQuery.validator.unobtrusive.adapters.add("greater", ["other"], function (options) {
options.rules["greater"] = "#" + options.params.other;
options.messages["greater"] = options.message;
});
jQuery.validator.addMethod('greaterThanDate', function (value, element, params) {
var date = value.toString().split('/');
var PassDay = date[0];
var PassMonth = date[1];
var passyear = date[2];
if (PassDay != null && PassMonth != null && passyear != null) {
var passDate = new Date(passyear, PassMonth - 1, PassDay);
var currentdate = new Date();
return passDate < currentdate;
}
return true;
}, '');
// and an unobtrusive adapter
jQuery.validator.unobtrusive.adapters.add('futuredate', {}, function (options) {
options.rules['greaterThanDate'] = true;
options.messages['greaterThanDate'] = options.message;
});
Но эта проверка отлично работает для меня во всех браузерах, кроме текущей стабильной версии Chrome.Я очень смущен.Кто-нибудь может мне помочь в решении этой проблемы?