amhed
amhed

Reputation: 3659

Preventing duplicates on knockout observable array

I have a ViewModel similar to this one (simplified):

var Person = function(){
    var self = this;
    self.Name = ko.observable();
    self.LastName = ko.observable();
    self.DriverId = ko.observable();
}

var MainViewModel = function(){
    var self = this;
    self.People = ko.observableArray();
}

I need to validate that the Driver Id is unique for each element of the array. What is the best way to do this? is it possible to create an MVC attribute? I couldn't find how since I've only done that for a specific class, not a collection.

Here is a JsFiddle with the ViewModel: http://jsfiddle.net/amhedh/VgJ59/6/

Upvotes: 2

Views: 3190

Answers (1)

Gaurav
Gaurav

Reputation: 8487

You can create a Knockout Custom Validator which will check your whole people array whenever the driverId property of any people object inside the array will change. Validator will return true or false according to the match ( if duplicate entry found it will return false otherwise true ) and further ko validation will automatically insert an error message for you.

I have created a custom validator which will do the job for you. Here is the validator:

var Unique = function(val, params)
{
  var isValid = true;
      ko.utils.arrayFirst(params[0](), function(item){
       if(val === item[params[2]]() && item !== params[1])
       {
           isValid = false;
           return true;
       }
      });
  return isValid;
};

And here is the usage :

....
.....
self.DriverId = ko.observable(person.DriverId).extend
 ({
   validation: { 
     validator: Unique, 
     message: 'DriverId is duplicate.', 
     params: [viewModel.People, self, 'DriverId']
   }
});
... 
....

Demo fiddle (Change the driverId textbox value to check validation)

Upvotes: 4

Related Questions