I'm using knockout-validation and am having a problem with the error messages not showing correctly after changing what observable an input field is bound to.
<div id="editSection" data-bind="if: selectedItem">
<div>
<label>First Name</label>
<input data-bind="value:selectedItem().FirstName" />
</div>
<div>
<label>Last Name</label>
<input data-bind="value:selectedItem().LastName" />
</div>
</div>
<br/>
<table data-bind='if: gridItems().length > 0'>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody data-bind='foreach: gridItems'>
<tr>
<td data-bind='text: FirstName' ></td>
<td data-bind='text: LastName' ></td>
<td><a href='#' data-bind='click: $root.editItem'>Edit</a></td>
</tr>
</tbody>
</table>
var lineViewModel = function(first, last) {
this.FirstName = ko.observable(first).extend({required:true});
this.LastName = ko.observable(last).extend({required: true});
this.errors = ko.validation.group(this);
}
var mainViewModel = function() {
this.gridItems = ko.observableArray();
this.gridItems([new lineViewModel('first1'), new lineViewModel(null,'last2')]);
this.selectedItem = ko.observable();
this.editItem = function(item){
if (this.selectedItem()) {
if (this.selectedItem().errors().length) {
alert('setting error messages')
this.selectedItem().errors.showAllMessages(true);
}
else{
this.selectedItem(item)
}
}
else
this.selectedItem(item)
}.bind(this)
}
ko.applyBindings(new mainViewModel());
Use this JSFiddle
Should I take another approach to this or should I do something different with the way that I am using ko.validation.group?
The validation is fine... your edit section has problems.
Use the with
binding. Never use someObservable().someObservableProperty
in a binding, it will not work like you might expect it. You should change the binding context.
<div id="editSection" data-bind="with: selectedItem">
<div>
<label>First Name</label>
<input data-bind="value: FirstName" />
</div>
<div>
<label>Last Name</label>
<input data-bind="value: LastName" />
</div>
</div>