我使用下面的代码验证输入的交货日期不应该低于今天的日期..为此目的,我在下面做了这样....
我正在使用jquery ...
进行自定义验证这是我的模特:
[UIHint("Date")]
[DeliveryDateCheck]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage="Required")]
public DateTime? DeliveryDate { set; get; }
这是服务器端代码验证
public class DeliveryDateCheck : ValidationAttribute, IClientValidatable
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string errorMessage = "Delivery date should be today date or Greater";
if(value != null)
{
DateTime dt = (DateTime)value;
if (dt.Date < DateTime.Now.Date)
{
return new ValidationResult(errorMessage);
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule mcvRule = new ModelClientValidationRule();
mcvRule.ValidationType = "checkdate";
mcvRule.ErrorMessage = "Delivery date should be today date or Greater";
yield return mcvRule;
}
}
这是客户端验证
$(document).ready(function () {
jQuery.validator.unobtrusive.adapters.add('checkdate', {}, function (options) {
options.rules['checkdate'] = true;
options.messages['checkdate'] = options.message;
});
jQuery.validator.addMethod('checkdate', function (value, element, params) {
if (value) {
var todayDate = new Date();
var compareDate = value.Date;
if (compareDate < todayDate) {
return false;
}
}
return true;
});
});
但是我得到这样的错误......
错误
0x800a138f - JavaScript runtime error: Unable to get property 'value' of undefined or null reference
我可以看到服务器端验证工作正常,但无法进行客户端验证 任何人都知道为什么我在这里得到错误.....
非常感谢提前
答案 0 :(得分:0)
不应该比较日期如下:
var compareDate = new Date(value);
答案 1 :(得分:0)
$(document).ready(function () {
jQuery.validator.unobtrusive.adapters.add('checkdate', {}, function (options) {
options.rules['checkdate'] = true;
options.messages['checkdate'] = options.message;
});
jQuery.validator.addMethod('checkdate', function (value, element, params) {
if (value) {
var todayDate = new Date();
var compareDate = new Date(value);
if (compareDate < todayDate) {
return false;
}
}
return true;
});
});