Skip to content
IanYates83 edited this page Oct 13, 2012 · 4 revisions

To get started with Knockout Validation, simply include the JavaScript file on your page and extend some of your observables:

// enable validation
ko.validation.init();

//start using it!
var myValue = ko.observable().extend({ required: true });

//oooh complexity
var myComplexValue = ko.observable().extend({ 
                     required: true,
                     minLength: 3,
                     pattern: {
                          message: 'Hey this doesnt match my pattern',
                          params: '^[A-Z0-9].$'
                     }
                 });

//or chaining if you like that
var myComplexValue = ko.observable()

myComplexValue.extend({ required: true })
            .extend({ minLength: 3 })
            .extend({ pattern: {
                 message: 'Hey this doesnt match my pattern',
                 params: '^[A-Z0-9].$'
            }});

//want to know if all of your ViewModel's properties are valid?
var myViewModel = ko.validatedObservable({
   property1: ko.observable().extend({ required: true }),
   property2: ko.observable().extend({ max: 10 })
});

// the all important applyBindings
ko.applyBindings( myViewModel );

console.log( myViewModel.isValid() ); //false

myViewModel().property1( 'something' );
myViewModel().property2( 9 );

console.log( myViewModel.isValid() ); //true