KO验证和bootstrap-datetimepicker

时间:2014-01-21 10:33:24

标签: knockout-validation bootstrap-datetimepicker

我正在尝试验证一次性字段大于另一次。时间由bootstrap-datetimepicker输入,并通过KO验证进行验证。

我的问题是验证似乎发生在文本框上的自动更正之前。

如何在应用自动更正后进行验证?

代码:

var vm = function () {
    var self = this;
    self.startTime = ko.observable().extend({ required: true });
    self.endTime = ko.observable()
    .extend({
        validation: {
            validator: function (val) {
                if (self.startTime() === '' || val === '') {
                    return true;
                }
                return new Date(val) > new Date(self.startTime());
            },
            message: 'Event must finish after it started'
        }
    });
    (function () {
        $('#event-start-time').datetimepicker({
            pickDate: false
        });
        $('#event-end-time').datetimepicker({
            pickDate: false
        });
        $('#event-end-time').on("change.dp", function (e) {
            //I've tried with and without this
            //self.endTime.valueHasMutated();
        });
    })();
};

结果:

enter image description here

Fiddle

1 个答案:

答案 0 :(得分:0)

可能有点迟,但这是我开发的:

假设您将结束日期作为可观察对象,然后使用自定义' dateBefore'验证

    this.endDate = ko.observable(new Date().addHours(3).toGMTString()).extend({
        required: true,
        dateBefore: self.startDate()
    });

创建自定义验证:

    ko.validation.rules['dateBefore'] = {
        validator: function (val, otherVal) {
            var d1 = new Date(val),
                d2 = new Date(otherVal);
            return d1 > d2;
        },
        message: 'The end date must be before the start date'
    };
    ko.validation.registerExtenders();

评论是否需要进一步解释