Reputation: 101150
I'm trying to get knockout validation to work in a small form with just one textbox and one select field.
The jsfiddle behavior is not the same as mine. I get a validation for the select list but not for the textbox. the fiddle doesn't give any validation (but reports that isValid()
is true).
I'm not a javascript guru and might have done something wrong. There is a fiddle here: http://jsfiddle.net/DzrqK/. The real page is loading the model in a bootstrap modal, but I've stripped that away for the fiddle.
HTML:
<div class="modal hide fade in" id="AddApplicationDialog" style="display: block;" aria-hidden="false">
<div class="modal-header">
<button type="button" class="close" aria-hidden="true" data-bind="click: Cancel">×</button>
<h3>Add aplication</h3>
</div>
<div class="modal-body">
<form action="#" data-bind="submit: Save" id="add-app-dlg" class="form" novalidate="novalidate">
<div class="alert alert-info">
We strongly recommend that you create different applications for different device types as it improves our error analytics.
<strong>OutOfMememoryException</strong> isn't as important in a mobile device as it's in a server with a lot of resources.
</div>
<div class="control-group">
<label class="control-label">Application name:</label>
<div class="controls">
<input type="text" data-bind="value: Name" name="Name" required="" minlength="3" />
</div>
</div>
<div class="control-group">
<label class="control-label">Application type:</label>
<div class="controls">
<select data-bind="value: ApplicationType" name="ApplicationType">
<option value=""></option>
<option value="Mobile">Mobile device</option>
<option value="Client">Client computer</option>
<option value="Server">Server</option>
</select>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<a href="#" class="btn btn-primary" data-bind="click: Save">Create aplication</a>
<a href="#" class="btn" data-bind="click: Cancel">Cancel</a>
</div>
</div>
Javascript:
var AddApplicationModel = function () {
var self = this;
this.inited = false;
this.Name = ko.observable().extend({ required: { message: 'Please supply your Name.' } });
this.ApplicationType = ko.observableArray().extend({ required: true });
this.Errors = ko.validation.group(self);
this.isValid = ko.computed(function () {
return self.Errors.length == 0;
});
this.Save = function () {
if (!self.isValid()) {
self.Errors.showAllMessages();
return;
}
//closing the modal and invoking a callback here in the real version
};
this.Cancel = function () {
//closing modal in the real version
};
ko.applyBindings(this, $('#AddApplicationDialog')[0]);
return this;
};
new AddApplicationModel();
Upvotes: 1
Views: 4015
Reputation: 139758
Two things are wrong in your fiddle:
the ko.validation.group(self)
returns an observable array by default so your isValid
should look like this:
this.isValid = ko.computed(function () {
return self.Errors().length == 0;
});
Demo JSFiddle.
Upvotes: 4