简体   繁体   English

Hapi / Joi验证

[英]Hapi/Joi validation

What does these with() and without() function do in 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');

Taken from the hapijs API Reference : 摘自hapijs API参考

object.with(key, peers)

Requires the presence of other keys whenever the specified key is present where: 只要指定的密钥存在于以下位置,就需要其他密钥的存在:

key - the reference key. key参考键。

peers - the required peer key names that must appear together with key. peers必须与密钥一起出现的必需对等密钥名称。 peers can be a single string value or an array of string values. peers可以是单个字符串值,也可以是字符串值数组。

Translated to your example that means "When the key username is present the key birthyear must also be present". 转换为您的示例,意思是“当密钥username存在时,密钥birthyear也必须存在”。

object.without(key, peers)

Forbids the presence of other keys whenever the specified is present where: 只要在以下位置存在指定项,就禁止存在其他键:

key - the reference key. key参考键。

peers - the forbidden peer key names that must not appear together with key. peers禁止与其他密钥一起出现的对等密钥名称。 peers can be a single string value or an array of string values. peers可以是单个字符串值,也可以是字符串值数组。

Translated to your example that means "When the key password is present then the key access_token is not allowed to be present too". 转换为您的示例,意思是“当存在密钥password也不允许存在密钥access_token ”。

.with(keyA, keyB) means that keyB must be present when keyA is present. .with(keyA, keyB)表示当存在keyA时必须存在keyB。

Your schema example makes no good use of .with() since "username" is a required key. 您的架构示例没有充分利用.with()因为“用户名”是必需的键。 You could then make "birthyear" required too. 然后,您也可以要求“生日”。

.without(keyA, keyB) means that keyB must NOT be present when keyA is present. .without(keyA, keyB)表示当存在keyA时不能存在keyB。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM