0

I have the following custom validtion rule for a voucher code which works and goes off to the server and validates my voucherCode correctly.

However there's 6 different failing states for a voucher - out of date, already redeemed, user not allowed etc etc.

I set the voucher message in the ajax response but this doesn't get propagated to the validation message.

Is it possible to have multiple messages for a single validation rule and change the message based on the result?

I couldn't find anything in the docs.

this.voucherMessage = "blah blah";
this.voucherCode = ko.observable("").extend({
  validation: {
    async: true,
    validator: function(val, params, callback) {
      var voucherCode;
      voucherCode = val.replace("-", "");
      return $.ajax({
        url: constantsRoutes.vouchers.getInfo(voucherCode),
        type: 'GET',
        success: callback
      }).done(function(response, statusText, xhr) {
        var isValid;
        _this.voucherDetails.setVoucher(response);
        _this.voucherMessage = _this.voucherDetails.voucherState.display();
        isValid = _this.voucherDetails.voucherState.state() === 0;
        return callback(isValid);
      });
    },
    message: this.voucherMessage
  }
Neil
  • 5,179
  • 8
  • 48
  • 87
  • [This](http://stackoverflow.com/questions/18129392/how-to-tie-together-ko-validation-errors-with-related-viewmodel-field-names#answer-24328733) might help you (in the changing of the message) – GôTô Jun 20 '14 at 22:11
  • Thanks - I found the answer which I've added below - the callback supports a complex object with `isValid` and `message` – Neil Jun 20 '14 at 22:42

1 Answers1

2

I should've read the source code in the first place - might be useful for someone else though

callback({
  isValid: isValid,
  message: _this.voucherDetails.voucherState.display()
});

This does the trick!

Neil
  • 5,179
  • 8
  • 48
  • 87
  • Nice, thank you for posting your solution to your own question so that others can make use of it – GôTô Jun 21 '14 at 17:21