Skip to content

Instantly share code, notes, and snippets.

@Ripley6811
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ripley6811/a02d50bae83e01f17744 to your computer and use it in GitHub Desktop.
Save Ripley6811/a02d50bae83e01f17744 to your computer and use it in GitHub Desktop.
KnockoutJS numeric validation function modified to allow a single period.
// Modified version of code at http://knockoutjs.com/documentation/extenders.html
// Allow a single period to pass when using "textInput" data-binding.
ko.extenders.numeric = function(target, precision) {
//create a writable computed observable to intercept writes to our observable
var result = ko.pureComputed({
read: target, //always return the original observables value
write: function(newValue) {
console.log(typeof newValue, newValue);
var current = target(),
roundingMultiplier = Math.pow(10, precision),
newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue),
valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;
//only write if it changed and allow a single period at end
if (String(newValue).indexOf('.') === String(newValue).length-1) {
target(newValue);
} else if (valueToWrite !== current) {
target(valueToWrite);
} else {
//if the rounded value is the same, but a different value was written, force a notification for the current field
if (newValue !== current) {
target.notifySubscribers(valueToWrite);
}
}
}
}).extend({ notify: 'always' });
//initialize with current value to make sure it is rounded appropriately
result(target());
//return the new computed observable
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment