无法获取未定义或空引用的属性值

本文关键字:引用 属性 获取 未定义 | 更新日期: 2023-09-27 18:09:47

我使用下面的代码来验证输入的交付日期不应该小于今天的日期。为此,我做了如下操作....

我正在使用自定义验证使用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

我可以看到服务器端验证工作正常,但不能做客户端验证有没有人知道为什么我在这里得到错误.....

many thanks in advance

无法获取未定义或空引用的属性值

不应该这样比较日期:

var compareDate = new Date(value);
  $(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;
    });
 });