条件验证不适用于匿名敲除验证规则 [英] Conditional validation not working for anonymous Knockout validation rule

查看:61
本文介绍了条件验证不适用于匿名敲除验证规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的视图模型中具有以下属性,这些属性使用敲除验证,其中之一是用于验证密码匹配的自定义验证.

I have following attributes in my viewmodel which use knockout validation,one of them is custom validation to check password match.

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,有人可以帮助我为什么会这样吗?自定义规则的条件验证?

I found that OnlyIf condition is working fine for model.Password depending on model.IsCredentialsRequired() but its not working for model.ConfirmPassword,Can somebody help me why this is happening?Is there any another way by which i can use conditional validation for custom rules?

预先感谢

推荐答案

淘汰赛验证当前不支持匿名规则使用'onlyIf'.但是自定义规则支持该功能.因此,您可以创建一个自定义规则,并在其中使用onlyIf:

knockout-validation does currently not support 'onlyIf' for anonymous rules. But it is supported for custom rules. Therefore you can create a custom rule and use onlyIf with that:

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/

这篇关于条件验证不适用于匿名敲除验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆