2

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.

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

OFFS. Thanks for pointing that out. The message I'm getting now is: TypeError: string is not a function. I'm assuming I need to pass a callback function?
Yeppers. I was just about to post the same thing. Thank you so much for the help. Obviously, I need more coffee.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.