Prevent knockout validation from evaluating on initial load


I have a simple view-model with a few required attributes… I want each input to highlight red if the corresponding property is not valid, but I don't want this highlighting to display when the page is initially loaded… only when a value changes or when the user tries to save / continue…

Right now it's validating the view-model on initial load because I'm specifying data-bind="css: { error: name.isValid() == false }", but I don't know of any other way to get this to work dynamically (similar to how jQuery unobtrusive validation works)…

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

<div data-bind="css: { error: !name.isValid() }">
    <input type="text" data-bind="value: name" />

Any ideas on how to make this work would be appreciated… Thanks!

Best Solution

A better approach is to configure knockout validation to decorate the element with the validationElement class. This is done by adding this configuration option:

ko.validation.configure({ decorateElement: true });

Click here to see a jsfiddle demonstrating this.


If you need to decorate the parent element, a more elegant and reusable solution is to apply this custom binding to the parent element.


ko.bindingHandlers.parentvalElement = {
    update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var valueIsValid = valueAccessor().isValid();
        if(!valueIsValid && viewModel.isAnyMessageShown()) {
        else {

And apply the binding in your HTML like so:

<form data-bind='submit:OnSubmit'>
    <label data-bind='parentvalElement:name'>
        <input data-bind="value: name" />
    <input type='submit' value='submit' />

Take a look at this updated jsfiddle to see it in action.