Skip to content

Validation Bindings

edmomot edited this page Apr 10, 2017 · 13 revisions

Knockout Validation comes with several built-in bindings!

validationMessage

If you want to customize the display of your objects validation message, use the validationMessage binding:

<div>
   <input type="text" data-bind="value: someValue"/>
   <p data-bind="validationMessage: someValue"></p>
</div>

validationOptions

For large form areas, use the validationOptions binding to specify validation options. This will cascade your options through the children of the container to which you apply to binding.

Use this for:

  • Custom Message Templates
  • Disabling auto-inserting of messages
  • Changing the Validation Message CSS Class
<div data-bind='validationOptions: { messageTemplate: "customMessageTemplate" }'>
    <label>Email: <input data-bind='value: emailAddress' required pattern="@"/></label>
    <label>Location: <input data-bind='value: location'/></label>
    <label>Age: <input data-bind='value: age' required/></label>
</div>

A good example for validationOptions is when you want to process error messages for a checkbox/radio button differently from the rest of the form. Say, you don't want them inserted between the input element and its label:

<!-- regular situation -->
<label for="e">Your E-mail</label>
<input id="e" type="text" data-bind="value: email" />
<!-- default error message will be inserted here-->

<!-- turn off auto insert messages for the checkbox below only -->
<label data-bind="validationOptions: {insertMessages: false}">
  <input type="checkbox" data-bind="checked: wantsSpam" />
  I want spam
</label>
<span class="validationMessage" data-bind="validationMessage: wantsSpam"></span>

validationElement

This sets the message as title attribute (tooltip) of the bound element. If the decorateInputElement option is true, it also toggles the CSS class 'validationElement' on the bound element. A different class can be configured using the errorElementClass option. The binding below applies the message as title to an input element. This is useful for use cases where you want to set the errorElementClass to a parent element, for example when you want to use the bootstrap validation classes.

<div>
   <label data-bind="validationElement: someValue"> <!-- the 'errorElementClass' will be added to this element too -->
     <input type="text" data-bind="value: someValue"/>
   </label>
</div>