Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joi Schema should contain one field or another

Tags:

javascript

joi

I'm looking into using Joi for api validation.

I can't seem to confirm whether my schema is correct in that I want either the email or mobile to be required (but they both can't be empty/non existent) - is the below correct?

var schemaForRegistration = Joi.object().keys({
      email: Joi.string().email(),
      mobile:Joi.number().integer()
}).without('email', 'mobile');

Thanks

like image 506
userMod2 Avatar asked Feb 18 '16 18:02

userMod2


People also ask

What is a joi schema?

Hapi Joi is an object schema description language and validator for JavaScript objects. With Hapi Joi, we create blueprints or schemas for JavaScript objects (an object that stores information) to ensure validation of key information.


1 Answers

It might be that or() is what you're after.

Try this:

const Joi = require('joi')

const schema = Joi.object().keys({
    email: Joi.string().email(),
    mobile: Joi.number().integer()
}).or('email', 'mobile')

Joi.validate({ email: '[email protected]', mobile: '999000999000' }, schema, console.log)
Joi.validate({ mobile: '999000999000' }, schema, console.log)
Joi.validate({ email: '[email protected]' }, schema, console.log)
Joi.validate({}, schema, console.log)

The final validation will fail because neither email nor mobile is present.

like image 82
Adrian Lynch Avatar answered Oct 18 '22 09:10

Adrian Lynch