12

我的视图模型中有以下使用淘汰赛验证的属性,其中之一是自定义验证以检查密码匹配。

model.Password = ko.observable()
                  .extend({ required: { message: "Password is required.", 
                        params: true,
                        onlyIf: function () { return model.IsCredentialsRequired(); }}
                    });


model.ConfirmPassword = ko.observable().
                        extend({ validation: { validator: mustEqual,
                        message: 'Passwords do not match.',
                        params: model.Password,               
                        onlyIf: function () { return model.IsCredentialsRequired(); } }
                    });

自定义验证功能的代码

var mustEqual = function (val, other) {
                return val == other();
            };

我发现该OnlyIf条件适用于model.Password取决于 model.IsCredentialsRequired()但不适用于model.ConfirmPassword,有人可以帮助我为什么会发生这种情况吗?有没有其他方法可以对自定义规则使用条件验证?

提前致谢

4

1 回答 1

18

淘汰验证目前不支持匿名规则的“onlyIf”。但它支持自定义规则。因此,您可以创建自定义规则并使用 onlyIf :

ko.validation.rules['confirmPasswordMatches'] = {
    validator: function (val, params) {
        var otherValue = params;
        return val === ko.validation.utils.getValue(otherValue);
    },
    message: 'Passwords do not match.',
};
ko.validation.registerExtenders();

function ViewModel() {
    var self = this;

    self.IsCredentialsRequired = ko.observable(true);

    self.Password = ko.observable()
        .extend({
            required: {
                message: "Password is required.",
                params: true,
                onlyIf: self.IsCredentialsRequired
            }
    });

    self.ConfirmPassword = ko.observable().
    extend({
            confirmPasswordMatches: {
            params: self.Password,
            onlyIf: self.IsCredentialsRequired
        }
    });

}

小提琴:http: //jsfiddle.net/delixfe/mFAEx/

于 2013-01-30T10:35:53.250 回答