验证Keystone.js中相互依赖的字段

Bra*_*don 2 mongoose node.js keystonejs

保存项目时,我正在尝试进行验证。这是我的简化模型:

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();
    }
});
Run Code Online (Sandbox Code Playgroud)

如果Sample模型isPublished设置为,truethumbnailImage尚未设置,我想提出一个错误。当我输入console.log()这些值时,我分别看到truefalse,但是在Keystone Admin中没有出现验证错误。

我浏览了Github上用于Keystone的示例应用程序,Mongoose文档中有很多示例,但是我还没有看到能够处理多个文档路径的示例。

使用2个字段(当前有12个upvotes)的猫鼬自定义验证的示例对我也不起作用。

我究竟做错了什么?我正在使用Mongoose 3.8.35。

Joh*_*yHK 5

您不应该!否定验证条件的第二部分,因为您当前正在标记一个不为空的验证错误。

因此将其更改为:

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();
    }
});
Run Code Online (Sandbox Code Playgroud)

请注意,Error在调用next报告验证失败时,还需要将错误字符串包装在一个对象中。