Knockout Validation - Process

by Cristian Trifan

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.2/knockout.validation.min.js"></script>
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>

<input type="text" data-bind="textInput: email" />
<button data-bind="click: addRule">Add Rule</button>

<hr />
    
<pre id="log"></pre>

CSS

pre {
    background-color: #fafafa;
    border: 1px solid #cccccc;
    padding: 10px;
}

input {
    padding: 4px 3px;
}

button {
    padding: 4px 10px;
}

JavaScript

ko.validation.init({messagesOnbModified: true, decorateElementOnModified: true}, true);


var _prevFn = ko.validation.validateObservable;

ko.validation.validateObservable = function(observable) {
    var child = document.createTextNode([
        new Date().toTimeString().substr(0, 9),
        'Validating... ', 
        ko.toJSON({rules: observable.rules.peek()}, null, 2),
        '\n',
        Array(60).join('-'),
        '\n',
        document.querySelector('#log').innerText
    ].join(''));
    document.querySelector('#log').innerHTML = '';
    document.querySelector('#log').appendChild(child);
};


function ViewModel() {
    var rules = [
        {required: true},
        {email: true},
        {minLength: 10},
        {maxLength: 255}
    ];
    var lastIndex = 0;
    
    this.email = ko.observable('').extend({validatable: true});
    
    this.addRule = function(viewModel) {
        if (lastIndex < rules.length - 1) {
            viewModel.email.extend(rules[lastIndex]);
            lastIndex++;
        }
    };
}


ko.applyBindings(new ViewModel());