JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-debug.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.js"></script>
<label>
<input type="checkbox" data-bind="checked: swap"> Swap computed read return value
</label>
<br />
<!--<input type="text" data-bind="value: compObs">-->
<select data-bind="options:listOptions, optionsText: 'description', optionsValue: 'id', value: compObs, optionsCaption: 'Choose option..'">
</select>
CSS
.validationMessage{
background-color: rgba(255,106,0,.37);
}
JavaScript
// This setting shows "This field is required" upon load
var showOnLoadSettings = {
messagesOnModified: false
};
var hideOnLoadSettings = {
messagesOnModified: true
};
// Swap with hideOnLoad settings and re-run fiddle to show intended behavior
ko.validation.init(showOnLoadSettings);
var VM = function() {
this.regObs = ko.observable("John");
this.altObs = ko.observable("");
this.swap = ko.observable(true);
this.listOptions = ko.observableArray([{
id: 1,
description: "first"
}, {
id: 2,
description: "second"
}, {
id: 3,
description: "third"
}]);
this.compObs = ko.pureComputed({
write: function(value) {
this.regObs(value);
},
read: function() {
return this.swap() ? this.altObs() : this.regObs();
},
owner: this
}).extend({
required: true
});
}
ko.applyBindings(new VM());