Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First item in errors() 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, when I add a task, it is invalid for some reason even when I have entered in the fields correctly. The console outputs [null]. Upon further investigation, it seems that even when I don't enter my fields correctly, the first item in my taskErrors array is always [null]. So it may looks like: [null], "This field is required.". Not sure what I've done wrong?

Edit

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

like image 549
CallumVass Avatar asked Jan 15 '23 01:01

CallumVass


2 Answers

your task attribute is observable(a function), so to apply validation to it you should pass the object with ().

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

You should be careful when your object is observable.

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

You can acces to his attribute like this:

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

Not like this :

console.log(self.task.description);

Task without () is a function not an object that's the trick.

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

Good luck

like image 88
Mounir Avatar answered Jan 17 '23 16:01

Mounir


Move the errors into the JobTask and the issue goes 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!');
        }
    };

}
like image 36
John Earles Avatar answered Jan 17 '23 16:01

John Earles