Configuring ViewModel Knockout to Validate

I am trying to figure out how to use the knockout verification plugin. Looking at the project’s website on github, there ’s a Getting Started section that describes how to set up a review model with validation. In this example, the ViewModel is declared as an inline object (is this the correct terminology?) 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 customize my view model using the following function:

 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 viewModelInstance not have an isValid method.

+4
source share
2 answers

ko.validatedObservable () is the key to validating the viewModel. It creates all the internal methods the plugin needs (there are more than isValid). You can still create instances with the function, but try wrapping it in ko.validatedObservable ():

 var viewModelInstance = ko.validatedObservable( new MyViewModel() ); 
+3
source

This is the definition from the source code and the only place it is used in the source is knockout.validation.js .

validatedObservable( ) is & ndash; and this one.

 ko.validatedObservable = function (initialValue) { if (!kv.utils.isObject(initialValue)) { return ko.observable(initialValue).extend({ validatable: true }); } var obsv = ko.observable(initialValue); obsv.errors = kv.group(initialValue); obsv.isValid = ko.observable(initialValue.isValid()); obsv.errors.subscribe(function (errors) { obsv.isValid(errors.length === 0); }); debugger; return obsv; }; 

In my experience, this is more of a problem than it costs - for example, it does not have the ability to specify a “deep” for the created “group”, and I think that it is really intended only for simple objects of the “one level” js.

If you have a complex model, your best bet is to do something similar and create an array of objects that you really want to check:

  var validatables = []; // if credit card is payment then validate payment details + address if (this.paymentMethod() == "Credit Card") { validatables.push(this.paymentDetails); validatables.push(this.billingAddress); if (this.shipToBillingAddress() == false) { validatables.push(this.shippingAddress); } } var group = ko.validation.group(validatables, { deep: true }); 
+1
source

Source: https://habr.com/ru/post/1494364/


All Articles