Last active
August 29, 2015 14:14
-
-
Save Ripley6811/a02d50bae83e01f17744 to your computer and use it in GitHub Desktop.
KnockoutJS numeric validation function modified to allow a single period.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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