KO validation with Bootstrap error and feedback? Can do.

I’ve been struggling to configure Knockout Validation to use Bootstrap error classes and form-control-feedback element. Finally, it’s working and now I’m going to brag about it. It’s quite simple really ;-)

  1. <div class="form-group has-feedback" data-bind="validationElement: myVar">
  2.   <label class="control-label" for="myVarId">Queue Name</label>
  3.   <input id="myVarId" class="form-control" type="text" data-bind="textInput: myVar" />
  4. </div>
  5.  
  6. <script type="text/html" id="myErrorTemplate">
  7.   <span class="help-block" data-bind="text: field.error, visible: field.isModified()"></span>
  8.   <span class="glyphicon glyphicon-remove form-control-feedback" data-bind="visible: field.isModified() &amp;&amp; !field.isValid()"></span>
  9. </script>

The interesting javascript part is just the configuration. Your validation rules and model bindings/observables are the usual:

  1. ko.validation.init({
  2.   errorElementClass: ‘has-error’,
  3.   messageTemplate: ‘myErrorTemplate’
  4. });

 

Tags: ,

Leave a Reply