Reputation: 2815
I am trying to use knockout.validation plugin. I want created a custom validation rule for checking the duplicate array item while making entry in the array. I tried this :
ko.validation.rules['duplicate'] = {
validator: function (val1, val2) {
},
message: 'The value is already exist'
};
ko.validation.registerExtenders();
Here val1
is the array and val2
is the parameter pass in with the extend method. The problem is, i don`t know how to access the current entered item in the array from custom validation function. help me please ?
Upvotes: 0
Views: 1991
Reputation: 7194
It would work better if you flip around the problem. Add the validation onto the text observable (or an observable object, if multiple fields are involved) that you are trying to add. Then when you trigger the add, check if the observable is valid. If it's valid then add it to the array.
http://jsfiddle.net/jearles/XY9XH/
--
<span>New Item: <input data-bind="value:newItem" /> <button data-bind="click: addItem">Add</button></span>
<div data-bind="foreach: items">
<span data-bind="text: $data"></span>
</div>
--
ko.validation.rules['duplicate'] = {
validator: function (item, array) {
return array.indexOf(item) == -1;
},
message: 'Value already exists!'
};
ko.validation.registerExtenders();
var ViewModel = function() {
var self = this;
self.items = ko.observableArray();
self.newItem = ko.observable().extend({duplicate: self.items});
self.addItem = function() {
if (self.newItem().length > 0 && self.newItem.isValid()) {
self.items.push(self.newItem());
self.newItem(null);
}
};
}
ko.applyBindings(new ViewModel());
Upvotes: 1