Knockout验证不会根据验证规范更新错误消息

时间:2014-05-19 09:14:09

标签: knockout.js durandal knockout-validation

我正在尝试根据提供的条件显示不同的验证消息,但消息未正确显示。此功能中使用的所有方法均可按要求正常工作。

我附上了代码:

self.pickupCloseTime.extend({
    required: {
        message: "Please select Close time.",
    },
    validation: {
        validator: function (val) {
            if (val == "") {
                this.message = "Please select Close time.";
                return false;
            }
            else if (self.pickupReadyTime() != "") {
                var readyTime = moment(self.pickupReadyTime(), "hh:mm A");
                var closeTime = moment(val, "hh:mm A");

                if (closeTime.diff(readyTime) > 0 
                      && (closeTime.diff(readyTime) / 3600) < 2000) {
                    this.message = 'Please select valid Close time.';
                    return false;
                }
                else if (closeTime.diff(readyTime) <= 0) {
                  this.message = "Close time should be greater than Ready time.";
                  return false;
                }
                return true;
            }
            else {
                this.message = 'Please select Ready Time first.'
                return false;
            }
        },
        message: "Close time should be greater than Ready time.",
        params: true
    }
});

请帮忙。

1 个答案:

答案 0 :(得分:0)

最佳做法是将它们分成更小的验证案例,每个验证案例都有自己的条件和消息。

您还可以将它们添加为自定义验证规则,以便重复使用,以下是一个示例:

define(['knockout',
    'data/settings',
    'services/resourceService'],
function (ko, settings, resourceService) {

    ko.validation.rules['closeTimeNotValid'] = {
        // check if close time is Valid
        validator: function (val) {
            //example rule
            return val != "" && val > 0;
        },
        message: "Please select valid Close time."
    };
            return ko.validation.rules;
});

然后,如果需要,您可以使用/重用此规​​则:

self.pickupCloseTime.extend({
    required: {
        message: "Please select Close time."
    },
    closeTimeNotValid: {
        message: "Message overrides the custom rule's message",
        //add more rules/conditions to the main one, you can also 
        //set params here to be used in the custom validation
        onlyIf: function () { return self.someOtherField(); }
    }
});