I'm trying to set up a validation group to display errors after a button's pressed.
My issue is I can't get the validation group to update correctly each time the validation error changes.
In my example, I can see the the .errors property of the field observable update correctly each time I leave the text box (intended). For the validation group, the documentation points to calling .showAllMessages() or evaluating the group itself.
I've created an example below. A summary of the behaviour I see:
In the example, I've set up these validations on a single field:
The view:
<label>Test number</label>
<input type="text" data-bind="value: myNumber"/>
<div>myNumber error: <span data-bind="text: myNumber.errors"/></div>
<div>Validation group:
<ul data-bind="foreach: validationGroup"><li data-bind="text: $data"></li></ul>
</div>
<button type="submit" class="btn" data-bind="click: testValidate">Update validation group</button>
The view model:
var viewModel = {
myNumber: ko.observable().extend({
maxLength: 10,
number: {
message: "Please ensure that myNumber contains only numeric characters"
},
required: {
message: "myNumber is required"
},
minLength: 3
})
};
viewModel.validationGroup = ko.validation.group([viewModel.myNumber]);
viewModel.testValidate = function () {
// Try both, to be sure...
viewModel.validationGroup.showAllMessages();
viewModel.validationGroup();
};
Well, looks like it's a bug from the older version of Knockout (v1.0.1).
The last released version is v1.0.2 (from Sept 2012), and the working sample below is from the GitHub latest: (last modified Oct 2013)
Here's a JS Fiddle of the same code above, working as intended: http://jsfiddle.net/overflew/JhWZq/1/
So the .showAllMessages() is all that's required to update the group:
viewModel.testValidate = function () {
viewModel.validationGroup.showAllMessages();
};
Reason for winding up with the old version: KO Validation via NuGet (Microsoft .NET's package management tool) was last updated June 2013 w/v1.0.1, which is now 1 or 2 versions behind.