You can add a trimming functionality to observables, e.g. adding a custom function to ko.subscribable.fn
as explained in another SO post:
ko.subscribable.fn.trimmed = function() {
return ko.computed({
read: function() {
return this();
},
write: function(value) {
this(value.trim());
this.valueHasMutated();
},
owner: this
}).extend({ notify: 'always' });
};
var vm = function () {
this.num = ko.observable().trimmed().extend({ number: true });
this.num(' 2 ');
}
ko.applyBindings(new vm());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script>
<input type="text" data-bind="value: num" />
P.S. Don't be tempted to add a trim()
call into Knockout validator plugin number
rule:
// this is the original 'number' rule implemetation, with a 'trim()' call added to it
ko.validation.rules['number'] = {
validator: function (value, validate) {
if (!validate) { return true; }
return ko.validation.utils.isEmptyVal(value) ||
(validate && /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value.trim()));
},
message: 'Please enter a number.'
};
... because you don't want the trimming to happen during validation, but much earlier, that is: during the writing.