我想将Knockout Validation和Knockout自定义绑定与输入掩码(http://robinherbots.github.io/jquery.inputmask/)一起使用。示例:钱输入框,我不希望用户首先能够输入任何字母字符,我也想同时限制最小和最大金额。
在我的JSFiddle中,您可以看到那些非自定义绑定的可观察对象具有工作验证,但其他观察者没有。
http://jsfiddle.net/csabatoth/LkqTU/24841/
<div>
<p>Title 1: <input data-bind='value: title1' /></p>
<p>Amount 1: <input data-bind='value: amount1' /></p>
<p>Title 2: <input data-bind='inputmask: { value: title2, mask: "*****" }' /></p>
<p>Amount 2: <input data-bind='inputmask: { value: amount2, mask: "money" }' /></p>
</div>
ko.bindingHandlers.inputmask =
{
init: function (element, valueAccessor, allBindingsAccessor) {
var mask = valueAccessor();
var observable = mask.value;
if (ko.isObservable(observable)) {
$(element).on('focusout change', function () {
if ($(element).inputmask('isComplete')) {
observable($(element).val());
} else {
observable(null);
}
});
}
if (mask.mask === "money") {
$(element).inputmask('decimal',
{
'alias': 'numeric',
'groupSeparator': ',',
'autoGroup': true,
'digits': 2,
'radixPoint': ".",
'digitsOptional': false,
'allowMinus': false,
'prefix': '$ ',
'placeholder': '0'
}
);
} else {
if (mask.regex)
$(element).inputmask('Regex', { regex: mask.mask });
else
$(element).inputmask(mask.mask);
}
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var mask = valueAccessor();
var observable = mask.value;
if (ko.isObservable(observable)) {
var valuetoWrite = observable();
$(element).val(valuetoWrite);
}
}
};
var ViewModel = function() {
var self = this;
self.convertMoneyToFloat = function (moneyVal) {
var value = parseFloat(moneyVal.replace(/[^\.\d]/g, ""));
return value;
}
self.title1 = ko.observable("T1").extend({ maxLength: 5 });
self.title1.subscribe(function (newValue) {
console.log("AJAX write T1 " + newValue);
});
self.amount1 = ko.observable(110.0).extend({ number: true, min: 10.0, max: 10000.0 });
self.amount1.subscribe(function (newValue) {
console.log("AJAX write A1 " + newValue);
});
self.title2 = ko.observable("T2").extend({ maxLength: 5 });
self.title2.subscribe(function (newValue) {
console.log("AJAX write T2 " + newValue);
});
self.amount2 = ko.observable(110.0).extend({ number: true, min: 10.0, max: 10000.0 });
self.amount2.subscribe(function (newValue) {
console.log("AJAX write A1 " + self.convertMoneyToFloat(newValue));
});
};
ko.applyBindings(new ViewModel());
答案 0 :(得分:2)
验证工作正常,你可以在这个小提琴中看到:http://jsfiddle.net/L5ndbnba/2/。
问题是,屏蔽字段不会自动显示消息,因此您应该通过添加<span data-bind="validationMessage: amount2"></span>
显式显示验证消息。
现在,由于屏蔽值存储在amount2中,您需要将验证规则应用于数值计算机以使它们正常工作:
self.amount2 = ko.observable(110.0);
self.amount2Numeric = ko.computed(function() {
return self.convertMoneyToFloat(self.amount2());
});
self.amount2Numeric.extend({ number: true, min: 10.0, max: 10000.0 });
以下是完整的工作小提琴:http://jsfiddle.net/L5ndbnba/3/