I have a situation where I need to check the maximum amount of a field in my view model. However, the maximum amount must be variable and calculated depending on the user interface element selected outside this model. I tried to include the observable as a parameter in my own validator, but it does not update when the value changes.
I have the feeling that as soon as the verification code is executed for the first time, it holds onto the parameters.
HTML list that does not use Knockout
<select id="ContentsReplacementAmount"> <option value="25000">£25000</option> <option value="50000">£50000</option> <option value="75000">£75000</option> </select>
Here is the dumb version of the code I'm using.
var SpecifiedValuablesViewModel = function (maxSpecifiedItemAmount) { var self = this; self.maxSpecifiedItemAmount = ko.observable(maxSpecifiedItemAmount); self.amountToAdd = ko.observable().extend({ validation: { validator: function (val, max) { return val <= max; }, message: 'The amount must be a maximum of £{0}', params: self.maxSpecifiedItemAmount() } }); }; var specifiedValuablesViewModel = new SpecifiedValuablesViewModel($('#ContentsReplacementAmount').val()); ko.applyBindings(ko.validatedObservable(specifiedValuablesViewModel), document.getElementById('SpecifiedValuables'));
Event outside maxSpecifiedAmount
$('#ContentsReplacementAmount').on('change', function () { specifiedValuablesViewModel.maxSpecifiedItemAmount(parseInt($(this).val())); });
My question is: how can I achieve this?
source share