KO.mapping + KO.validation,如何使用验证映射验证两个属性

时间:2013-02-26 22:30:43

标签: knockout.js knockout-mapping-plugin knockout-validation

 var validationMapping = {

        emailAddress: {
            create: function (options) {
                return ko.observable(options.data).extend({ required: true }).extend({email:true});
            }
        },
        emailAddressConfirm: {
            create: function (options) {
                return ko.observable(options.data).extend({ required: true }).extend({ email: true })
                .extend({equal: emailAddress});}}};

上面是我在映射模型时使用的验证映射

 $.post('getaccountdata', {},
        function (data) {
            if (data != "") {
                myViewModel = ko.validatedObservable(ko.mapping.fromJS(data, validationMapping));
                ko.applyBindings(myViewModel);
            }
        });

问题是这似乎不起作用。看来传递给“相等”验证函数的emailAddress对象不是视图模型中的可观察对象。指定“其他”可观察对象的正确语法是什么?

1 个答案:

答案 0 :(得分:1)

几个月后,但无论如何;) 我找到的唯一方法是在绑定后扩展验证:

...
myViewModel = ko.validatedObservable(ko.mapping.fromJS(data, validationMapping));
ko.applyBindings(myViewModel);
myViewModel().emailAddress.extend({ equal: myViewModel().emailAddressConfirm });