Search code examples
javascriptknockout.jsknockout-validation

Knockout decorateInputElement configuration


I can't make decorateInputElement working on this very basic example: Plunker.

HTML

<label data-bind="text: isValid()"></label>
<div>
  <label>DateTime</label>
  <input id="datePicker" data-bind="value: dateTime" />
  <label data-bind="text: dateTime"></label>
</div>

JS

$(function() {
  ko.validation.init({
    insertMessages: false,
    decorateInputElement: true
  });

  function ViewModel() {
    var self = this;
    self.dateTime = ko.observable().extend({
      required: true
    });
  }

  var viewModel = ko.validatedObservable(new ViewModel())();
  ko.applyBindings(viewModel);
});

CSS

.validationMessage {
  color: red;
}

.validationElement {
  background: red;
}

Normally, validationElement class should be applied when the field is empty but nothing happens (insertMessages works, however). Any idea?


Solution

  • Please don't use the validation plugin from cdnjs: it is quite old and full of bugs.

    If you use the latest version of the plugin from github: http://github.com/Knockout-Contrib/Knockout-Validation, then your code is working fine: see in this updated Plunker

    As a side note: you can make this working with the cdnjs version but there the configuration property is called decorateElement, so you need to write:

    ko.validation.init({
       insertMessages: false,
       decorateElement: true
    });
    

    Demo Plunker.