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?
Here is a fiddle I created of the problem: http://jsfiddle.net/5kh6h/1/
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
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!');
}
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With