我想使用带有输入掩码的 Knockout Validation 和 Knockout 自定义绑定(http://robinherbots.github.io/jquery.inputmask/)。示例:货币输入框,我一开始就不希望用户可以输入任何字母字符,并且我还想同时限制最小和最大金额。
在我的 JSFiddle 中,您可以看到那些不是自定义绑定的 observables 具有有效的验证,而其他的则没有。
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());