簡體   English   中英

Hapi Joi 驗證 - 驗證單個字符串

[英]Hapi Joi validation - validate single string

我想對單個字符串進行一些基本驗證,這是一個請求 header X-Value 下面是我的嘗試。

問題是即使沒有X-Value header 存在,它也總是返回“成功”。

  const mySchema = Joi.string().min(2).max(30).required();
  const value = req.get('X-Value');
  const { myError } = mySchema.validate(value);
  if(myError){
    return res.status(401).json({ error: myError.details[0].message });
  }

  return res.send('success');

如何在不將其放入 object 的情況下驗證這一點?

您正在從驗證 function 中解構myError 但是沒有這樣的事情。 您需要破壞error並像這樣使用:

const mySchema = Joi.string().min(2).max(30).required();
const value = req.get('X-Value');
const { error } = mySchema.validate(value);

if (error) {
  return res.status(401).json({ error: error.details[0].message });
}

return res.send("success");

暫無
暫無

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

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