I have attempted implementing the suggestions below but neither seemed to trigger the required reaction each time a value was updated. This may due to my implementation as I'm new to Knockout.
I have an observable (Amount) which is bound to a TextBoxFor.
@Html.TextBoxFor(m => m.Amount, new { type = "number", data_bind = "value: Amount" })
When a value is entered it needs to be validated to ensure it doesn't exceed 999999. In addition to this, if the value is less than 50 then it needs to be set to 50. These checks needs to be made each time the 'Amount' changes.
var viewModel = {
Amount: ko.observable().extend({numeric: 0, max: 999999})
};
I've tried implementing the solutions (in the answer to my previous post) but I couldn't get these to work.
The best I have come up with is creating a computed as follows. This checks the input value and updates correctly on the first attempt. Subsequent value changes do not trigger a change on the screen but stepping through the code, do seem to update the ViewModel.Amount value.
@Html.TextBoxFor(m => m.Amount, new { type = "number", data_bind = "value: amountMin" })
quoteVehicleViewModel.VehicleMileage = ko.observable(0);
viewModel.amountMin = ko.computed({
read: function () {
return viewModel.Amount();
},
write: function (value) {
if (value < 50) {
viewModel.Amount(50);
}
}
}).extend({ numeric: 0, max: 999999 });
** A "viewModel.Amount()" entered in the Console shows the value as being 1000 but the value on screen still shows as the value entered.
Any assistance gratefully received
John