我该如何同时使用 Knockout Validation 和 Knockcout X-editable?

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

我在我的 ASP.NET 项目中使用 Bootstrap、Knockout 和带有 knockout 绑定的 X-editable。 我无法进行验证。根据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."

没错,调用了 isValid。我正在像这样设置敲除变量(敲除验证):

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

在我的 cshtml 中,我包含 bootstrap-editable.cssbootstrap-editable.jsknockout-{version}.jsknockout.validation.jsknockout.x-editable.js。我在控制台上没有错误消息,x-editable 对话框很好地弹出并且值发生了变化。然而,验证并没有发生。我认为 x-editable 会将验证中继到我自己用敲除验证定义的内容。我应该实现任何 isValid 函数还是什么?如果我实施 isValid,我将如何触发 Knockout.Validation?我迷路了。

验证仅适用于开箱即用的值和 selectedOptions,如果您使用自定义绑定,则需要使用 ko.validation.makeBindingHandlerValidatable

ko.validation.makeBindingHandlerValidatable("selectedOptions");

我的配置实际上是这样的:self.num1 = ko.observable().extend({ number: true, min: 0.01, max: 10e10, numeric: 2 });。最后一件事 "numeric" 是我自己的验证绑定,它以不发生验证的方式干扰 ko 验证(也没有错误消息)。

如果您想使用自己的验证,请按照以下步骤操作:https://github.com/Knockout-Contrib/Knockout-Validation/wiki/User-Contributed-Rules

关于 knockout x-editable 验证绑定需要考虑的另一件事:

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.

所以您会看到更多变化,这些变化是由绑定本身引起的,而不仅仅是您的值变化。如果您订阅绑定变量,则需要以某种方式过滤掉它们。