Search code examples
knockout.jstwitter-bootstrap-3knockout-validationx-editable

How do I supposed to use Knockout Validation and Knockcout X-editable at the same time?


I'm using Bootstrap, Knockout and X-editable with knockout bindings in my ASP.NET project. I cannot get the validation to work. According to knockout x-editable (https://github.com/brianchance/knockout-x-editable):

"If you are using knockout.validation, I have wired up a call to the observable's isValid for editable.validate. To work, this has to push the new value into the observable, then validate, then revert back. If you have subscribed to changes, you will see them. Not the best choice, but works."

That's true, the isValid is called. I'm setting up the knockout variable like this (Knockout validation):

self.num1 = ko.observable().extend({ number: true, min: 0.01, max: 10e10 });

In my cshtml I include bootstrap-editable.css, and bootstrap-editable.js, knockout-{version}.js, knockout.validation.js, knockout.x-editable.js. I have no error message on the console, the x-editable dialog pops up nicely and the value change takes place. However the validation just doesn't happen. I thought x-editable will relay the validation to what I defined with knockout validation by itself. SHould I implement any isValid function or something? How would I trigger Knockout.Validation if I implement an isValid? I'm lost.


Solution

  • My configuration was actually like this: self.num1 = ko.observable().extend({ number: true, min: 0.01, max: 10e10, numeric: 2 });. The last thing "numeric" is my own validation binding and it interferes with the ko validation in a way that no validation happens (no error message either).

    If you want to use own validation, follow this: https://github.com/Knockout-Contrib/Knockout-Validation/wiki/User-Contributed-Rules

    Another thing to consider about knockout x-editable validation binding:

    To work, this has to push the new value into the observable, then validate, then revert back. If you have subscribed to changes, you will see them.

    So you'll see more changes, which are induced by the binding itself, and not just your value change. You need to filter those out somehow, if you subscribe to a bound variable.