簡體   English   中英

驗證Keystone.js中相互依賴的字段

[英]Validating fields that depend on each other in Keystone.js

保存項目時,我正在嘗試進行驗證。 這是我的簡化模型:

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();
    }
});

如果Sample模型的isPublished設置為true但未設置thumbnailImage我想引發一個錯誤。 當我用console.log()值時,我分別看到truefalse ,但是在Keystone Admin中沒有出現驗證錯誤。

我瀏覽了Github上用於Keystone的示例應用程序,Mongoose文檔中有很多示例,但是我還沒有看到能夠處理多個文檔路徑的示例。

使用2個字段 (當前帶有12個upvotes)的貓鼬自定義驗證的示例對我也不起作用。

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

你不應該! 否定驗證條件的第二部分,因為您當前正在標記一個不為空的驗證錯誤。

因此將其更改為:

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();
    }
});

請注意,在調用next報告驗證失敗時,還需要將錯誤字符串包裝在Error對象中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM