I'm using Knockout.Validation and I'd like to be able to display an error summary where each line displays the error message (obviously!) and also the field name on the view model related to it, e.g.
- Age - please enter a number
- Date of birth - please enter a proper date
So far I've got a validatedObservable wrapping my view model, and this puts an errors array on my viewmodel automatically, containing all my errors. However I can't see any easy way to retrieve which field each error relates to.
I know I could traverse the view model myself, building up an errors collection of my own from the isValid property - is this my only option though?
Once I have the field name, I can map my validation summary to the related "friendly" label for that field (e.g. "Date of birth" rather than "DateOfBirth").
Here's a simplified version of the code I have so far:
ViewModel
function PersonModel(){
var self = this;
self.Age = ko.observable().extend({ number: true});
self.DateOfBirth = ko.observable({ date: true});
self.Validate = function() {
if (!self.isValid()) {
self.errors.showAllMessages();
return false;
}
return true;
};
ko.validation.init({
grouping: { deep: true, observable: true },
registerExtenders: true,
messagesOnModified: true,
insertMessages: true
});
ko.applyBindings(ko.validatedObservable(new PersonModel()));
Html
<ul data-bind='foreach: model().errors' class="message">
<li>
<span data-bind='text: $data'></span>
</li>
</ul>
Many Thanks