marucc
2/24/2015 - 6:51 AM

KnockoutJSで、Validation通した値でcssの変更を行いたい場合のサンプル

KnockoutJSで、Validation通した値でcssの変更を行いたい場合のサンプル

<!DOCTYPE html>
<title>sample</title>
<style>.error { color:red }</style>
<div id="main">
    <input type="text" data-bind="value: name, valueUpdate: 'afterkeydown'">
    <span data-bind="css: { error: is_error }">*required</span>
    <hr>
    Name: <span data-bind="text: name"></span>
</div>

<script src="http://knockoutjs.com/downloads/knockout-3.3.0.js"></script>
<script>
function FormViewModel() {
    this.name = ko.observable('Name');
    this.is_error = ko.pureComputed({
        read: function () {
            return this.name().replace(/\s/g, '').length == 0;
        },
        owner: this
    })
}
ko.applyBindings(new FormViewModel());
</script>