4

If I extend a knockout observable like so

var x = ko.observable().
extend({ 
     pattern : { 
         params: someRegex,
         message: "An error"
    }
})
.extend({ 
     pattern : { 
         params: someMoreRegex,
         message: "Another error"
    }
})

Is this a valid extension for a knockout observable (i.e. multiple pattern extensions)?

The regex for the second pattern is not being validated at all. In some cases it does get triggered but shows the first patterns error message. I have recently upgraded form 1.0.2 to 2.0.3 knockout validation and this has since broken but cannot seem to put a finger on why this is no longer working.

Maciej Grzyb
  • 543
  • 2
  • 10
Sim
  • 570
  • 1
  • 10
  • 22

1 Answers1

7

From this (admitedly, quite old) Github issue, I concluded that this isn't supported by the validation library...

A quick fix could be to create anonymous custom rules that borrow the validator method from the pattern extension.

An example (which doesn't make sense, but shows how you can combine two patterns with their own errors):

this.name = ko.observable("").extend({
  validation: [{
      validator: ko.validation.rules['pattern'].validator,
      message: "Must be lowercase",
      params: /^[a-z]+$/
    }, {
      validator: ko.validation.rules['pattern'].validator,
      message: "Must be uppercase",
      params: /^[A-Z]+$/
    }
  ]
});

You could maybe clean this code up a bit by creating a factory method that returns the required objects, or create a custom rule that takes an array of regular expressions and an array of error messages.

user3297291
  • 22,592
  • 4
  • 29
  • 45
  • Works with ko.validation 1.0.2 just not 2.0.3... Tried with both worked on 1. must have become unsupported in later versions – Sim Jun 27 '16 at 14:40
  • Weird, because the post I linked to dates from the v1.0.2 release... If you're sure it _was_ supported before and isn't anymore, and feel it should be, I'd suggest stepping through the code or studying the source on GitHub. If you can link to both a working and not working example (in a fiddle), somebody might be able to help you out. Personally, I'd accept that moving up a major version requires some syntax changes and code updates... – user3297291 Jun 27 '16 at 14:52