I\'ve seen this post - it shows one possible solution. But I would like to have a more elegant way of doing masked input.
It should also play nicely with knockout valida
Just take the code from the answer in that link and put it in a extender (Written on free hand, can have errors)
ko.extenders.masked = function(observable, options) {
return ko.computed({
read: function() {
return '$' + this.observable().toFixed(2);
},
write: function(value) {
// Strip out unwanted characters, parse as float, then write the raw data back to the underlying observable
value = parseFloat(value.replace( /[^\.\d]/g , ""));
observable(isNaN(value) ? 0 : value); // Write to underlying storage
}
});
};
edit: You probably want to supply the mask as a options instead of having it hardcoded to USD etc
update: If you want to use the mask plugin from riceboyler's answer but with extenders you can do
ko.extenders.mask = function(observable, mask) {
observable.mask = mask;
return observable;
}
var orgValueInit = ko.bindingHandlers.value.init;
ko.bindingHandlers.value.init = function(element, valueAccessor) {
var mask = valueAccessor().mask;
if(mask) {
$(element).mask(mask);
}
orgValueInit.apply(this, arguments);
}
http://jsfiddle.net/rTK6G/