20

I am using the Knockout Validation plugin and setting an observable as required using the extender:

myObservable.extend({required:true});

Is it possible for me to remove the extender after adding it?

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
Jonas Stawski
  • 6,682
  • 6
  • 61
  • 106

2 Answers2

38

You can remove all the validation relates properties form an observable which were added by the ko validation with calling:

myObservable.extend({validatable: false});

Or if you want to only remove the required validation you can remove it from the rules collection:

myObservable.rules.remove(function (item) {
        return item.rule == "required";
    });
}

Demo JSFiddle.

But the ko validation has support for conditional validation, so you can specify some condition when the validation should work so maybe this is what you need:

myObservable.extend({
    required: {
        message: "Some message",
        onlyIf: function () { return //some condition; }
    }
});
nemesv
  • 138,284
  • 16
  • 416
  • 359
  • 1
    the onlyIf was exactly what I needed, but how about what I asked about removing the extender? Is that supported by knockout? – Jonas Stawski Jun 15 '13 at 15:36
  • 2
    No, you cannot remove an extender unless the extender itself provides a way to "revert" its own changes. In the case of the ko validation the `myObservable.extend({validatable: false});` call exactly does this it removes all the the validation related stuff which was added by `.extend({required:true});` or any of the other rules. – nemesv Jun 15 '13 at 15:40
2

nemesv answer works with a small typo correction - the function in the remove(...) call should return a boolean value (i.e. '==' instead of '='):

myObservable.rules.remove(function(item) {
  return item.rule == "required";
});

Demo: JSFiddle

Community
  • 1
  • 1
mikemsq
  • 71
  • 6