简体   繁体   中英

Hapi/Joi validation

What does these with() and without() function do in Joi validation?

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 :

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.

Translated to your example that means "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.

Translated to your example that means "When the key password is present then the key access_token is not allowed to be present too".

.with(keyA, keyB) means that keyB must be present when keyA is present.

Your schema example makes no good use of .with() since "username" is a required key. You could then make "birthyear" required too.

.without(keyA, keyB) means that keyB must NOT be present when keyA is present.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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