7

我正在尝试使用来自 GitHub 的 Knockoutjs 验证插件。大多数似乎都可以正常工作,但是当我尝试使用扩展验证 mustEqual(password/confirm password) 时,它似乎什么也没做。我错过了什么?

我非常想学习这种扩展器技术以备将来使用。

(这整个 html 和 javascript 也通过 AJAX 调用加载到页面。如果这与它有任何关系。)

我的 javascript

    function UserAccount(data) {
        var self = this;
        self.Password = ko.observable(data.Password).extend({ required: true, minlength: 6, message: "Password is required", maxLength: 12 });

        self.Firstname = ko.observable(data.Firstname).extend({ required: true, minlength: 6, message: "Firstname is required", maxLength: 40 });
        self.Lastname = ko.observable(data.Lastname).extend({ required: true, minlength: 6, message: "Lastname is required", maxLength: 40 });
        self.Email = ko.observable(data.Email).extend({ required: true, minlength: 6, message: "Email is required", email: true, maxLength: 90 });
        self.ConfirmPassword = ko.observable().extend({ mustEqual: self.Password()});
        ...........................Other Code............
        }

    ko.validation.rules['mustEqual'] = {
        validator: function (val, otherVal) {
            alert("Hello");
            return val === otherVal;
        },
        message: 'The field must equal {0}'
    };
    $(document).ready(function () {


        ko.applyBindings(new UserAccount(initdata), $("#UserAccount").get(0));
        ko.validation.registerExtenders();

    });
4

1 回答 1

10

您的自定义验证器代码正常。但是您没有正确调用该ko.validation.registerExtenders();方法。

虽然没有明确说明,但您需要在调用ko.validation.registerExtenders(); 之前调用ko.applyBindings

因此,要修复您的代码,您只需要编写:

$(document).ready(function () {
    ko.validation.registerExtenders();
    ko.applyBindings(new UserAccount(initdata), $("#UserAccount").get(0));
});

但是您将面临另一个问题:mustEqual验证器用于与静态值进行比较,因此如果您想将两个属性(如密码)与确认密码进行比较,它将不起作用。

您需要的是用户贡献的“相同”验证器

ko.validation.rules['areSame'] = {
    getValue: function (o) {
        return (typeof o === 'function' ? o() : o);
    },
    validator: function (val, otherField) {
        return val === this.getValue(otherField);
    },
    message: 'The fields must have the same value'
};

你可以使用什么:

self.Password = ko.observable(data.Password).extend({
    required: true,
    minlength: 6,
    message: "Password is required",
    maxLength: 12
});
self.ConfirmPassword = ko.observable().extend({
    areSame: self.Password
});

演示JSFiddle

于 2013-09-23T19:06:50.127 回答