In a ViewModel I have a few properties which have required and regular expression validations (on the same property) as follows:
// ...other properties...
MaxDays: ko.observable("").extend({
required: { message: "You have to specify the maximum number of days." },
pattern: {
message: "Please enter a valid number.",
params: '[0-9]+$',
maxLength: 10
}
}),
// ...other properties...
I’m using Jasmine to test and I noticed that if I assign a value that doesn’t match the expression, the value is ignored and it runs its own test for "required" as if there’s no data in that property.
// ... describe, other "it" statements, etc...
it("should complain if there's incorrect data", function () {
viewModel.MaxDays("Zweiundzwanzig");
expect(viewModel.errors().length).toBeGreaterThan(0);
expect(viewModel.errors()).toContain('Please enter a valid number.');
console.log(viewModel.errors());
});
// ...
When I run the test it fails. the errors collection is filled with an error but not because I entered a string when it should be a number. It fails because it thinks that property is empty. I get the error message from "required" instead of the message from "pattern":

The funny part is that it works on the UI, so if I go on the field bound to that property and type a string value, it will fire the regex validation and put the correct error message beside the field.
Can anyone point out what I’m missing here?
knockout.validation.group.errors() does currently not update correctly if the error type changes (see https://github.com/ericmbarnard/Knockout-Validation/issues/218).
I assume that this is your problem. Try to set ‘MaxDays’ to a correct value and then to the invalid one. That should fix the test if that was your problem.