0

所以我一直在关注本教程它向您展示了如何验证日期之间的比较。我在评论的第一个代码块中遇到错误,它说“无法获取未定义或空引用的属性'元素'”,它源于这行代码 customValidation.formValidator = $(event.data .source).closest('form').data('validator') 有没有人知道解决这个问题的方法,所以我没有收到错误。我正在使用最新的不显眼的验证

window.customValidation = window.customValidation ||
{
    relatedControlValidationCalled: function (event) {
        if (!customValidation.activeValidator) {
            customValidation.formValidator = $(event.data.source).closest('form').data('validator');
        }

        // code error below
        customValidation.formValidator.element($(event.data.target));
    },
    relatedControlCollection: [],
    formValidator: undefined,
    addDependatControlValidaitonHandler: function (element, dependentPropertyName) {
        var id = $(element).attr('id');
        if ($.inArray(id, customValidation.relatedControlCollection) < 0) {
            customValidation.relatedControlCollection.push(id);
            $(element).on(
                'blur',
                { source: $(element), target: $('#' + dependentPropertyName) },
                customValidation.relatedControlValidationCalled);
        }
    }
};

适配器:

$.validator.unobtrusive.adapters.add('comparedates', ['otherpropertyname', 'allowequality'],
    function (options) {
        options.rules['comparedates'] = options.params;
        if (options.message) {
            options.messages['comparedates'] = options.message;
        }
    }
);

验证器方法:

$.validator.addMethod('comparedates', function (value, element, params) {
    var otherFieldValue = $('input[name="' + params.otherpropertyname + '"]').val();
    if (otherFieldValue && value) {
        var currentValue = Date.parse(value);
        var otherValue = Date.parse(otherFieldValue);
        if ($(element).attr('name').toLowerCase().indexOf('begin') >= 0) {
            if (params.allowequality) {
                if (currentValue > otherValue) {
                    return false;
                }
            } else {
                if (currentValue >= otherValue) {
                    return false;
                }
            }
        } else {
            if (params.allowequality) {
                if (currentValue < otherValue) {
                    return false;
                }
            } else {
                if (currentValue <= otherValue) {
                    return false;
                }
            }
        }
    }
    customValidation.addDependatControlValidaitonHandler(element, params.otherpropertyname);
    return true;
}, '');
4

1 回答 1

0

也许您在表单进入 DOM 之前加载此代码太早了。确保您的代码受 $(document).ready(your code here);

于 2014-02-02T14:43:23.453 回答