JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script>
Gender:
<select data-bind="value: memberType,
options: memberTypeSource,
optionsText: 'text',
optionsValue: 'id',
optionsCaption: 'Please select'"></select>
<br />Seeking:
<select data-bind="selectedOptions: seekingTypes,
options: memberTypeSource,
optionsText: 'text',
optionsValue: 'id', validationCore: seekingTypes"
multiple></select>
<br />
<button type="button" data-bind='click: doValidation'>Submit</button>
JavaScript
ko.validation.init();
function isNotUndefined(val) {
return (typeof val != "undefined");
}
function isArrayNotEmpty(val) {
return (val.length > 0);
}
var viewModel = function () {
var self = this;
self.memberType = ko.observable().extend({
validation: {
validator: isNotUndefined,
message: 'Please select gender'
}
});
self.seekingTypes = ko.observableArray().extend({
validation: {
validator: isArrayNotEmpty,
message: 'At least one option is required'
}
});
self.memberTypeSource = [{
id: 1,
text: 'Man'
}, {
id: 2,
text: 'Woman'
}];
self.errors = ko.validation.group(self);
self.doValidation = function () {
console.log('error count=' + self.errors().length);
if (self.errors().length == 0) {
console.log('Yay.');
} else {
self.errors.showAllMessages(true);
}
};
return {
memberType: self.memberType,
seekingTypes: self.seekingTypes,
memberTypeSource: self.memberTypeSource,
errors: self.errors,
doValidation: self.doValidation,
}
};
//ko.validation.makeBindingHandlerValidatable('selectedOptions');
ko.applyBindings(new viewModel);