I am attempting to figure out how to use the knockoutjs validation plugin. Looking at the project site on github, there is a getting started section describing how to set up a view model with validation. In this example the ViewModel is declared as an inline object (is this the correct terminology?) like so:
var myViewModel = ko.validatedObservable({
property1: ko.observable().extend({ required: true }),
property2: ko.observable().extend({ max: 10 })
});
console.log(myViewModel.isValid()); //false
myViewModel().property1('something');
myViewModel().property2(9);
console.log(myViewModel.isValid()); //true
However, I would like to set up my viewmodel using a function like this:
function MyViewModel() {
var self = this;
self.property1 = ko.observable().extend({ required: true });
self.property2 = ko.observable().extend({ max: 10 });
};
var viewModelInstance = new MyViewModel();
console.log(viewModelInstance.isValid()); //false
viewModelInstance.property1('something');
viewModelInstance.property2(9);
console.log(viewModelInstance.isValid()); //true
The problem is that I get a script error saying that my viewModelInstance
object does not have a method isValid
.
ko.validatedObservable() is the key to validation of viewModel. It creates all internal methods needed by the plugin (there is more than isValid). You can still create instances with function but try wrapping it in ko.validatedObservable() :
var viewModelInstance = ko.validatedObservable( new MyViewModel() );