JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.2.0.debug.js"></script>
<script src="https://raw.github.com/ericmbarnard/Knockout-Validation/master/Src/knockout.validation.js"></script>
<fieldset>
<legend>User: <span data-bind='text: errors().length'></span>errors</legend>
<label>Number:
<input data-bind='value: number' />
</label>
</fieldset>
<button type="button" data-bind='click: submit'>Submit</button>
CSS
label {
display: block;
}
.validationMessage {
color: Red;
}
.customMessage {
color: Orange;
}
JavaScript
ko.validation.rules.pattern.message = 'Invalid.';
ko.validation.configure({
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true,
messageTemplate: null
});
ko.extenders.coerceMin = function (target, enable) {
//collect rule values
var minRule = ko.utils.arrayFirst(target.rules(), function (val) {
return val.rule === "min"
});
if (minRule === null) {
throw Error("coerceMin extender must be used in conjunction with the 'min' knockout validation rule");
}
var minValue = minRule.params;
//listen for changes and coerce when necessary
var subscription = null;
if (enable && !subscription) {
subscription = target.subscribe(function (newValue) {
if (!isNaN(newValue)) {
var newValueAsNum = parseFloat(+newValue);
var valueToWrite = newValueAsNum < minValue ? minValue : newValueAsNum;
//only write if it changed
if (valueToWrite !== newValue) {
target(valueToWrite);
}
}
});
} else {
if (subscription) {
subscription.dispose();
}
}
//return the original observable
return target;
};
ko.validation.registerExtenders();
var viewModel = {
number: ko.observable().extend({
number: true,
min: 50,
max: 99
}).extend({
coerceMin: true
}),
submit: function () {
if (viewModel.errors().length == 0) {} else {
viewModel.errors.showAllMessages();
}
}
};
viewModel.errors =...