I am building a Knockout project and love the Knockout-Validation library from https://github.com/Knockout-Contrib/Knockout-Validation but am having a problem trying to validate numbers using the min/max attributes.
My question is probably a total newbie one, but here it goes: I have no problem validating a text field to satisfy a statically set min and max such as:
this.text_bet = ko.observable().extend({ required: true, min: 0, max: 100, step: 1 }); // Sets max statically to 100
But if I try:
this.max = ko.observable() or this.max = ko.computed(); // Some independent variable in my view model
this.text_bet = ko.observable().extend({ required: true, min: 0, max: this.max, step: 1 }); // Sets max dynamically
It fails. I've tried making the field observable, computed, and validatedObservable and the "max: self.max" only seems to use the initial undefined value. An explanation of how to set these min & max properties dynamically would be greatly appreciated!
A shortened version of the specific code I'm trying to solve is below.
<!DOCTYPE html>
<head>
<title></title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.debug.js"></script>
<script src="js/knockout.validation.js"></script>
<!-- <script src="http://cdn.strategiqcommerce.com/ajax/libs/knockout-validation/1.0.2/knockout.validation.min.js"></script>-->
<style type="text/css">
.RedBox {
border-color: red;
color: red;
}
</style>
</head>
<html>
<body>
--- Poker Game ---
<br />
<input id="max" type="text" data-bind="valueUpdate: 'afterkeydown', value: text_max" />Enter max bet allowed (between 1-1000)
<span data-bind="validationMessage: text_max, text: '*Amount required between 1-1000!'" class="RedBox"></span>
<br />
<input id="Text1" type="text" data-bind="valueUpdate: 'afterkeydown', value: text_bet" />
<span data-bind="text: 'Player bet (Enter bet between 1 - ' + text_max() + ')'"></span>
<span data-bind="validationMessage: text_bet, text: '*Amount required between 1-' + max()" class="RedBox"></span>
<br />
<script type="text/javascript">
function GameModel() {
var self = this;
this.text_max = ko.observable().extend({ required: true, min: 1, max: 1000, step: 1 }); // Allow a max amount between 1-1000
this.text_bet = ko.observable().extend({ required: true, min: 0, max: (this.max != null) ? this.max : 0, step: 1 });
this.max = ko.computed(function () {
if (self.text_max() != null && !parseInt(self.text_max()).isNaN) { // Check if max has been entered yet
return parseInt(self.text_max());
}
else {
return 0;
}
});
};
$(function () {
model = new GameModel();
ko.validation.init({ insertMessages: false, decorateElement: true, errorClass: "RedBox" });
ko.applyBindings(model);
});
</script>
</body>
</html>