Knockout Validation
A KnockoutJS Plugin for model and property validation
Contributors:
- Eric Barnard
- Steve Greatrex
- Cristian Trifan
- Andy Booth
- Michal Poreba
- and many others!
License: MIT
Install
Bower
bower install knockout-validation --save
NuGet
PM> Install-Package Knockout.Validation
NPM
npm install knockout.validation --save
CDN
cdnjs
- https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.4/knockout.validation.js
- https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.4/knockout.validation.min.js
jsdelivr
- https://cdn.jsdelivr.net/npm/knockout.validation@2.0.4/dist/knockout.validation.js
- https://cdn.jsdelivr.net/npm/knockout.validation@2.0.4/dist/knockout.validation.min.js
Getting Started
//start using it!var myValue = ko; //oooh complexityvar myComplexValue = ko; //or chaining if you like thatvar myComplexValue = ko myComplexValue ; //want to know if all of your ViewModel's properties are valid?var myViewModel = ko; console; //false ;; console; //true
see more examples on the Fiddle: http://jsfiddle.net/KHFn8/5424/
Native Validation Rules
Required:
var myObj = ko;
Min:
var myObj = ko;
Max:
var myObj = ko;
MinLength:
var myObj = ko;
MaxLength:
var myObj = ko;
Email:
var myObj = ko;
... and MANY MORE
Much thanks to the jQuery Validation Plug-In team for their work on many of the rules
Custom Validation Rules
Custom Rules
Custom Rules can be created using the simple example below. All you need is to define a validator function and a default message.
The validator function takes in the observable's value, and the params
that you pass in with the extend
method.
kovalidationrules'mustEqual' = { return val === params; } message: 'The field must equal {0}';kovalidation; //the value '5' is the second arg ('params') that is passed to the validatorvar myCustomObj = ko;
Learn more about Custom Rules on the WIKI
Or Check out our User-Contributed Custom Rules!
HTML5 Validation Attributes
Required:
Min:
Max:
Pattern:
Step:
Special Note, the 'MinLength' attribute was removed until the HTML5 spec fully supports it
Knockout Bindings
ValidationMessage
If you want to customize the display of your objects validation message, use the validationMessage
binding:
Check out more on Validation Bindings
Remote Validation Rules
Check out our Async Validation and jQuery AJAX Validation
Localization
Add a reference to the localization js files after the Knockout Validation plugin
Apply localized messages
kovalidation;