knockout-validators /


Why another knockout validation plugin?

Something just didn't quite feel right about [Knockout-validation][ko-validation].

Having said that, lots of things I have done with this plugin are based on concepts used there.

Getting Started

Instead of using .extend(), you use .validate() to apply a validator:

var value = ko.observable().validate({required: true});

value.errors();     // -> ["This value is required"]
value.errors();     // -> []

As you see, the .errors() property of the observable contains an array of validation errors based on the current value of the observable. Empty implies the value is valid.

You can remove a validator that has already been applied:

value.validate({required: false});
value.errors();     // -> []

You can also pass a message string to an existing validator:

value.validate({required: "Enter a value, tiger"});
value.errors();     // ["Enter a value, tiger"]

Note: any truthy value will cause a validator to come into effect: a string will be used as the message, a function will be used as the test.

Custom Validators

You can pass in an object containing the validation data:

value = ko.observable().validate({
  number: {
    validator: function(obj) {
      return obj === Number(obj) + "";
    message: "You must enter a valid number",
    html5attr: {attr: "pattern", value: "[0-9]*\.*[0-9]*"}

One a validator has been applied like this, you can then still use the forms described above:

value.validate({number: false});
value.validate({number: "Enter a number, tiger"});

You can add a reusable validator to ko.subscribable.fn.validate.defaultValidators:

ko.subscribable.fn.validate.defaultValidators['integer'] = {
  message: "This value must be a whole number",
  validator: function(value) { return value === parseInt(value, 10) + "";},
  html5attr: {attr: "pattern", value: "-?[0-9]+"}

HTML5 Attributes

If this is present on a validator, it will apply this attribute to the element.

Knockout Bindings

<form data-bind="allValid: $root, submit: sendData">
  <input type="text" data-bind="value: someValue">
  <!-- validation errors will automatically be inserted here -->
  <input type="submit" value="Okay">

Included validators

  • required
  • number
  • integer
  • min
  • max
  • minLength
  • maxLength
  • regex

These are all demonstrated in examples/index.html.