Search code examples
validationknockout.jsknockout-validation

Re-evaluate error message on dependant field with knockout validation


So I'm trying to get some validation to work with knockout validation. I created this fiddle to demonstrate my problem: https://jsfiddle.net/utjmLhxa/7/

When I change "quantity" and I already have an error message for "double quantity", I would like it to update the error message. It seems to disappear when the validation is valid, but it doesn't update if it is still invalid.

Is it possible to get knockout validation to re-evaluate the text? And if so, how? It seems to do some re-evaluatoin since the error disappears when the field is valid.

Example:

  1. Enter 2 in Quantity
  2. Enter 2 in Double quantity, shows error that it must be at least 4
  3. Enter 3 in Quantity, error message for Double quantity is still the same
  4. Enter 1 in Quantity, error message for Double quantity disappears

Here's the jsfiddle code:

<div id="vm">
  <span>Quantity</span>
  <input type="number" data-bind="value: quantity"/><br/>
  <span>Double quantity</span>
  <input type="text" data-bind="value: doubleQuantity"/>
</div>

ko.validation.registerExtenders();
var Vm = function(){
    var self = this;
    self.quantity = ko.observable().extend({ max: 5 });
    self.doubleQuantity = ko.observable().extend({validation: {
                validator: function (val) {
                    this.message = 'must be at least ' + self.quantity() * 2
                    return val >= 2 * self.quantity();
                },
                message: ''
            } });
};
ko.applyBindings(new Vm(), document.getElementById('vm'));

using https://knockoutjs.com/downloads/knockout-2.2.1.js and https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/1.0.2/knockout.validation.min.js


Solution

  • It looks like the error message doesn't get updated if the dependent field modifies (tried but couldn't manage to make it work).

    A workaround would be to trigger a re-evaluation on the doubleQuantity, simulating that the value has changed by calling valueHasMutated on the observable whenever the dependent changes. Add the following inside and at the end of your VM:

    self.quantity.subscribe(function(){
      self.doubleQuantity.valueHasMutated();
    });
    

    Working fiddle