Проверяйте список последовательных дат с помощью плагина jQuery Validate - PullRequest
0 голосов
/ 29 октября 2009

Я использую плагин jQuery Validate для проверки моей формы. У меня есть список дат, который генерируется динамически. Может включать от о до х количество дат. Мне нужно проверить, что этот список дат находится в последовательности, и что любая дата ближе к концу списка не предшествует дате, которая появляется раньше в списке.

Я изучил функции addMethod и addClassRules, чтобы добавить эти пользовательские правила, но я все еще не уверен, как реализовать это, не вызывая неудачу проверки всего списка дат, если только одна из них вышла из строя.

Кто-нибудь делал этот тип проверки раньше с плагином Validate?

Сейчас я использую метод Validate () для добавления правил в javascript, а не для добавления классов к элементам. Вот пример того, что я делаю сейчас:

$('#SaveForm').validate(
            {
                focusInvalid: false,
                errorContainer: errorContainer,
                errorLabelContainer: $("ol", errorContainer),
                wrapper: 'li',
                highlight: function(element) {
                    $(element).addClass('field-validation-error');
                    $(element).addClass('input-validation-error');
                },
                unhighlight: function(element) {
                    $(element).removeClass('field-validation-error');
                    $(element).removeClass('input-validation-error');
                },
                invalidHandler: function() {
                    $('#notifyBar').showNotifyBar({
                        notifyText: 'There are errors on the form. Please see the bottom of the page for details',
                        backgroundColor: '#FF0000'
                    })
            },
            rules: {
                SystemComment: {
                    maxlength: 8000
                },
                WorkComment: {
                    maxlength: 8000
                },
                DispositionGroup: {
                    required: true
                },
                DispositionCategory: {
                    required: true
                },
                DispositionDetail: {
                    required: true
                },
                NextWorkDate: {
                    required: true,
                    date: true
                }
            },
            messages: {
                SystemComment: {
                    maxlength: "System Comment max length is 8000 characters"
                },
                WorkComment: {
                    maxlength: "Work Comment max length is 8000 characters"
                },
                DispositionGroup: {
                    required: "Disposition Group is required"
                },
                DispositionCategory: {
                    required: "Disposition Category is required"
                },
                DispositionDetail: {
                    required: "Disposition Detail is required"
                },
                NextWorkDate: {
                    required: "Next Work Date is required",
                    date: "Next Work Date must be in mm/dd/yyyy format"
                }
            }
        });

Я добавлял эти методы для проверки, но это приводит к тому, что все поля не проходят проверку, если только одно из них завершается с ошибкой:

jQuery.validator.addMethod("currency", function(value, element) { return this.optional(element) || /^(\d{1,3})(\.\d{1,2})?$/.test(value); }
, "Payment Amount must be in currency format xx.xx");

jQuery.validator.addMethod("paymentDateCheck", validatePaymentDates, "Payment Date(s) must be in sequential order and may not be prior to today");
jQuery.validator.addMethod("paymentAmountCheck", validatePaymentAmounts, "Total Payment Amount cannot exceed the Customer Balance");

jQuery.validator.addClassRules({
    paymentAmountField: {
        required: true,
        currency: true,
        paymentAmountCheck: true
    },
    paymentDateField: {
        required:true,
        date:true,
        paymentDateCheck:true
    }
});

jQuery.extend(jQuery.validator.messages, {
    required: "Payment Date and Payment Amount are required",
    date: "Please specifiy valid date(s)",
    currency: "Amount must be in currency format (00.00)"
});

1 Ответ

0 голосов
/ 29 октября 2009

хорошо, я получил это на работу. Вот моя довольно наивная реализация:

1. Добавьте пользовательский метод проверки:

$.validator.addMethod("paymentDate", function(value, element) {
    return this.optional(element) || validatePaymentDate(value, element);
}, "Payment Date(s) is required, must be in date format, and must be in order");

2. Добавьте правило класса (элемент должен содержать класс paymentDateField

$.validator.addClassRules({
    paymentDateField: {
        required: true,
        date: true,
        paymentDate: true
    }
});

3. Реализуйте функцию validatePaymentDate:

function validatePaymentDate(value, element) {
    var paymentDates = $('.paymentDateField');
    var dateArray = new Array();
    var arrayIndex = 0;
    var currentElementIndex = 0;
    var isValid = true;

    $(paymentDates).each(function() {
        var currentElementVal = $(this).val();
        dateArray[arrayIndex] = currentElementVal;

        if (currentElementVal == $(element).val()) {
            currentElementIndex = arrayIndex;
            return false;
        }

        arrayIndex++;
    });

    for (var x = 0; x <= arrayIndex; x++) {
        console.log('array val: ' + dateArray[x]);
        console.log('dateVal: ' + value);

        if (x > currentElementIndex) {
            isValid = new Date(dateArray[x]) > new Date(value);
        }

        if (x < currentElementIndex) {
            isValid = new Date(dateArray[x]) < new Date(value);
        }
    }

    return isValid;
}

Функция может быть реорганизована для устранения большого количества циклов, но она дает желаемый эффект Только поля даты, которые находятся вне последовательности, помечены как недействительные.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...