簡體   English   中英

如何使用 joi 設置正確的模式和驗證?

[英]How to set up a proper schema and validation using joi?

我目前正在嘗試使用 joi 包設置驗證,但我遇到了一些最有可能與語法有關的問題。

我設置的模式是一個相當簡單的模式,它檢查數字是否有效和/或數據庫中是否存在 id。

export default router.post('/', async function(req, res, next) {
  const Joi = require('joi');
  // for testing
  if (!Object.keys(req.body).length) {
    req.body = {'tId':'123456789'}
  }

  const data = req.body;

  const schema = Joi.object().keys({
    tId: Joi.string.tId.required()
  });

  Joi.validate(data, schema, (err, value) => {

    if(err){
      res.status(404).json({
        status: 'error',
        message: 'tId not found',
        data: data
      });
    } else {
      res.json({
        status: 'success',
        message: 'Person found',
        data: Object.assign(22, value)
      });
    }
  });
})

我目前得到的錯誤是tId: Joi.string.tId.required()

UnhandledPromiseRejectionWarning: TypeError: 無法讀取未定義的“必需”屬性

我目前的研究主要圍繞以下鏈接:

https://www.digitalocean.com/community/tutorials/how-to-use-joi-for-node-api-schema-validation

我試圖模仿本教程實現的概念,我認為我對它的工作原理有一些不錯的想法,但我只是在庫的語法方面遇到了一些問題。

任何能夠充分利用 joi 庫的鏈接、視頻、項目等都會非常有幫助。

正如您所猜測的,這只是一個語法錯誤。 更新這部分:

const schema = Joi.object().keys({
    tId: Joi.string().required()
});

Joi.validate ,我假設你是 Joi v15 或更低版本,這里是你正在尋找的文檔 - https://joi.dev/api/?v=15.1.1#string---inherits-from -任何

暫無
暫無

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

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