user3595398
user3595398

Reputation: 123

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');

Upvotes: 1

Views: 1140

Answers (2)

trixn
trixn

Reputation: 16309

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".

Upvotes: 2

Carsten
Carsten

Reputation: 878

.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.

Upvotes: 0

Related Questions