Knockout Validation : Select
HTML
<script src="https://rawgithub.com/ericmbarnard/Knockout-Validation/master/Src/knockout.validation.js"></script>
<table>
<tr>
<td>
<select data-bind='options: industries, optionsValue: "code", optionsText: "description", optionsCaption: "Please select...", value: selection, validationElement: selection'></select>
</td>
</tr>
<tr>
<td>Selection:
<input data-bind='value: selectionText, valueUpdate: "afterkeydown"'></input>
</td>
</tr>
<tr>
<td><button data-bind='click: performValidation'> Validate</button></td>
<tr>
</table>
CSS
.has-error.has-feedback{
border: 1px solid red;
}
JavaScript
ko.validation.init({
decorateInputElement: true,
decoreateSelectElement: true,
errorElementClass: "has-error has-feedback",
insertMessages: false,
messagesOnModified: true,
});
var vm = {
industries: [{
"code": "00",
"description": "Unclassified",
"parent": null
}, {
"code": "01",
"description": "Amusement\/Arcade",
"parent": null
}],
selection: ko.observable().extend({
required: {
message: "Please select an industry."
}
}),
selectionText: ko.observable().extend({
required: true
})
}
vm.selection.subscribe(function (nv) {
vm.selectionText(nv)
})
vm.performValidation = function () {
ko.validation.group(vm).showAllMessages()
if (vm.errors().length > 0) {
console.log("Prevent something")
} else {
console.log("Good to go!")
}
}
// Are you using this on page load? ..that'll trigger the message
//ko.validation.group(vm).showAllMessages()
ko.applyBindings(vm);