Reputation: 34593
I'm trying to do validation when saving an item. Here's my pared-down model:
Sample.add({
isPublished: { type: Types.Boolean, default: false },
thumbnailImage: { type: Types.CloudinaryImage, folder: 'samples/thumbnails' },
});
Sample.schema.pre('validate', function(next) {
if (this.isPublished && !(_.isEmpty(this.thumbnailImage.image))) {
next('Thumbnail Image is required when publishing a sample');
}
else {
next();
}
});
I want to raise an error if a Sample
model has isPublished
set to true
but a thumbnailImage
hasn't been set. When I console.log()
the values, I see true
and false
respectively, but no validation error is raised in Keystone Admin.
I've looked through the sample applications on Github for Keystone, and the Mongoose docs have plenty of examples, but I haven't seen any that handle multiple document paths.
The example at: mongoose custom validation using 2 fields (currently with 12 upvotes) isn't working for me either.
What am I doing wrong? I'm using Mongoose 3.8.35.
Upvotes: 2
Views: 1660
Reputation: 312115
You shouldn't be !
negating the second part of your validation condition, as you're currently flagging a validation error when it's not empty.
So change it to:
Sample.schema.pre('validate', function(next) {
if (this.isPublished && _.isEmpty(this.thumbnailImage.image)) {
next(Error('Thumbnail Image is required when publishing a sample'));
}
else {
next();
}
});
Note that you also need to wrap your error string in an Error
object when calling next
to report a validation failure.
Upvotes: 6