Knockout Validation disable validation

Homer picture Homer · Nov 15, 2012 · Viewed 10.3k times · Source

I have ko.observableArrays with validation on the items. The user can mark a item as deleted. When it is marked as deleted, I need to disable validation on that item.

How do you dynamically disable validation?

Example: http://jsfiddle.net/3RZjT/2/

<div data-bind="foreach: names">
    <input data-bind="value: name, valueUpdate: 'afterkeydown'" /> <a data-bind="click: deleteMe, text:deleted()?'undelete':'delete'" href="#">delete</a><br/>
</div>

function Person(name){
    var self = this;
    self.name = ko.observable(name).extend({ required: true});
    self.deleted = ko.observable(false);
    self.deleteMe = function(){ 
        self.deleted(!self.deleted());
        self.deleted.extend({ validatable: !self.deleted()});
    };
}

var viewModel = {
    names: ko.observableArray([new Person("Ken"), new Person("")])
};

ko.applyBindings(viewModel);

Answer

Anders picture Anders · Nov 15, 2012

Update Old answer not valid for the Knockout-Contrib version of Validation (Thats the branch with active development)

https://github.com/Knockout-Contrib/Knockout-Validation

Use the onlyIf option like

this.enable = ko.observable(true);
this.required = ko.observable().extend({ required: { onlyIf: this.enable } });

Old answer

Try

this.property.extend({ validatable: false }); // disables all validation for property

or

this.property.extend({ required: false }); // disables required validation for property