Native Rules - Required

How to use Required rule.

by Cristian Trifan

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-debug.js"></script>
<script src="https://rawgit.com/Knockout-Contrib/Knockout-Validation/master/Dist/knockout.validation.js"></script>
<div class="page-title">
    <h1>Native Rules - <em class="rule-name">Required</em></h1>
    <div class="outline">
        <p>
            <span>This example shows how to use the <var>required</var> rule.</span>
        </p>
    </div>
</div>

<div class="example">

    <label>Name: </label>

    <input type="text" data-bind="textInput: name" />
    <!-- Validation message will be automatically inserted here -->
</div>

<hr>
<div class="inspect">
    <pre class="view-model" data-bind="text: ko.toJSON($data, null, 2)"></pre>
    <pre class="validation-state" 
        data-bind="text: ko.toJSON({isModified: name.isModified, isValid: name.isValid, error: name.error, rules: name.rules}, null, 2)">
</pre>
</div>

CSS

input {
    margin-right: 5px;
    padding: 4px 6px;
    outline: none;
}
 label {
     padding: 0 6px;
 }

.example {
    margin-bottom: 20px;
}
.validationElement {
    border: 1px dotted #b94a48;
}
.validationMessage {
    color: #b94a48;
}

pre {
    background-color: #fafafa;
    border: 1px solid #ccc;
    padding: 10px;
    position: relative;
    line-height: 20px;
}
pre.view-model:after {
    position: absolute;
    top: 5px;
    right: 5px;
    content: 'View Model';
    text-transform: uppercase;
    font-weight: bold;
    color: #444;
}
pre.validation-state:after {
    position: absolute;
    top: 5px;
    right: 5px;
    content: 'Validation State';
    text-transform: uppercase;
    font-weight: bold;
    color: #444;
}

.page-title {
    background-color: #fafafa; 
    border: 1px solid #efefef;
    overflow: hidden;
    margin-bottom: 20px;
    padding: 0 20px;
}

.page-title .rule-name {
    color: #b94a48;
}

JavaScript

//
// Feel free to change these configuration values and see
// how they affect the functionality.
//
ko.validation.init({
    // We want the messages to show right away
    messagesOnModified: false,
    
    // We want to decorate the input element right away
    decorateInputElement: true,
    decorateElementOnModified: false
});

var viewModel = {
    name: ko.observable('').extend({required: true})
};

ko.applyBindings(viewModel);