条件验证不适用于匿名Knockout验证规则

时间:2013-01-30 10:15:05

标签: knockout.js knockout-validation

我的viewmodel中有以下属性使用敲除验证,其中一个是自定义验证来检查密码匹配。

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,有人可以帮我解释为什么会这样吗?有吗?我可以用任何其他方式对自定义规则使用条件验证吗?

提前致谢

1 个答案:

答案 0 :(得分:17)

敲门验证目前不支持匿名规则的'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/