Search code examples
knockout.jsknockout-validation

Compare and validate selected value in two dropdown lists


I want to validate that selected item in a dropdown isn't selected in other dropdown.

I've created a fiddle to try, but it is not working:

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


Solution

  • I have updated your fiddle

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

    you had to move the following code up so it would be available at the time of assignment.

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

    the ohter thing was that you were assigning the self.selectedDatabase2 2 times to the params property of the validations

    good luck with it