The first element in error () is [null]

I have the following code:

function JobTask() { var self = this; self.description = ko.observable('').extend({ required: true }); self.priority = ko.observable('').extend({ number: true, required: true }); self.complete = ko.observable(false); } function CreateJobViewModel() { var self = this; self.task = ko.observable(new JobTask()); self.taskErrors = ko.validation.group(self.task); self.addTask = function () { if (self.taskErrors().length) { console.log(self.taskErrors()); self.taskErrors.showAllMessages(); } else { ... } }; } 

The problem is that when I add a task, it is for some reason incorrect, even if I entered the fields correctly. The console displays [null] . Upon further investigation, it seems that even if I do not enter my fields correctly, the first element in my taskErrors array taskErrors always [null] . It might look like this: [null], "This field is required." . Not sure what I did wrong?

Edit

Here is the fiddle I created from the problem: http://jsfiddle.net/5kh6h/1/

+4
source share
2 answers

Move the errors to JobTask and the problem JobTask away.

http://jsfiddle.net/jearles/5kh6h/4/

-

 function JobTask() { var self = this; self.description = ko.observable('').extend({ required: true }); self.priority = ko.observable('').extend({ number: true, required: true }); self.complete = ko.observable(false); self.errors = ko.validation.group(self); } function CreateJobViewModel() { var self = this; self.task = ko.observable(new JobTask()); self.addTask = function() { if (self.task().errors().length) { console.log(self.task().errors()); self.task().errors.showAllMessages(); } else { alert('Success!'); } }; } 
+4
source

the attribute of your task is observable (function), so to apply verification to it, you must pass the object using ().

 self.taskErrors = ko.validation.group(self.task()); 

You must be careful when your object is observable.

 self.task = ko.observable(new JobTask()); 

You can access its attribute as follows:

 console.log(self.task().description); 

Not this way:

 console.log(self.task.description); 

A task without () is not an object, but a trick.

Here is your working fiddle: http://jsfiddle.net/mounir/5kh6h/5/

Good luck.

+5
source

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


All Articles