比较并验证两个下拉列表中的选定值

时间:2014-04-03 12:08:06

标签: knockout.js knockout-validation

我想验证下拉菜单中的所选项目是否未在其他下拉菜单中选中。

我创造了一个小提琴尝试,但它不起作用:

ko.validation.configure({
    decorateElement: true,
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: false,
    parseInputAttributes: true,
    messageTemplate: null
});

var ViewModel = function () {
    var self = this;

    self.databases = ko.observableArray([{
        Name: "DB1",
        Id: 1
    }, {
        Name: "DB3",
        Id: 3
    }]);

    self.databases2 = ko.observableArray([{
        Name: "DB3",
        Id: 3
    }, {
        Name: "DB4",
        Id: 4
    }]);

    self.selectedDatabase = ko.observable();
    self.selectedDatabase2 = ko.observable();

/*  self.selectedDatabase = ko.observable().extend({
        validation: {
            validator: notEqual,
            params: self.selectedDatabase2
        }
    });

    self.selectedDatabase2 = ko.observable().extend({
        validation: {
            validator: notEqual,
            params: self.selectedDatabase2
        }
    });

    var notEqual = function (val, other) {
        return val =! other();
    };
    */

    ViewModel.errors = ko.validation.group(self);

    return self;
};

ko.applyBindings(new ViewModel());

JSFiddle

1 个答案:

答案 0 :(得分:1)

我已更新您的fiddle

http://jsfiddle.net/GrAFk/2/

您必须移动以下代码,以便在分配时可用。

var notEqual = function (val, other) {
    console.log(other());
    return val =! other();
};

更糟糕的是你将self.selectedDatabase2分配2次到验证的params属性

祝你好运