簡體   English   中英

Hapi / Joi驗證

[英]Hapi/Joi validation

Joi驗證中的with()和without()函數有什么作用?

const schema = Joi.object().keys({
    username: Joi.string().alphanum().min(3).max(30).required(),
    password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/),
    access_token: [Joi.string(), Joi.number()],
    birthyear: Joi.number().integer().min(1900).max(2013),
    email: Joi.string().email()
}).with('username', 'birthyear').without('password', 'access_token');

摘自hapijs API參考

object.with(key, peers)

只要指定的密鑰存在於以下位置,就需要其他密鑰的存在:

key參考鍵。

peers必須與密鑰一起出現的必需對等密鑰名稱。 peers可以是單個字符串值,也可以是字符串值數組。

轉換為您的示例,意思是“當密鑰username存在時,密鑰birthyear也必須存在”。

object.without(key, peers)

只要在以下位置存在指定項,就禁止存在其他鍵:

key參考鍵。

peers禁止與其他密鑰一起出現的對等密鑰名稱。 peers可以是單個字符串值,也可以是字符串值數組。

轉換為您的示例,意思是“當存在密鑰password也不允許存在密鑰access_token ”。

.with(keyA, keyB)表示當存在keyA時必須存在keyB。

您的架構示例沒有充分利用.with()因為“用戶名”是必需的鍵。 然后,您也可以要求“生日”。

.without(keyA, keyB)表示當存在keyA時不能存在keyB。

暫無
暫無

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

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