Hapi/Joi 验证

Hapi/Joi validation

这些 with() 和 without() 函数在 Joi 验证中有什么作用?

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 Reference:

object.with(key, peers)

Requires the presence of other keys whenever the specified key is present where:

key - the reference key.

peers - the required peer key names that must appear together with key. peers can be a single string value or an array of string values.

翻译成你的例子,意思是 "When the key username is present the key birthyear must also be present"。

object.without(key, peers)

Forbids the presence of other keys whenever the specified is present where:

key - the reference key.

peers - the forbidden peer key names that must not appear together with key. peers can be a single string value or an array of string values.

翻译成您的示例,意思是 "When the key password is present then the key access_token is not allowed to be present too"。

.with(keyA, keyB)表示keyA存在时keyB必须存在

您的架构示例没有很好地利用 .with(),因为 "username" 是必需的键。然后,您也可以使 "birthyear" 成为必填项。

.without(keyA, keyB) 表示当 keyA 存在时,keyB 必须 NOT 存在。