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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With