How to allow any other key in Joi [duplicate]
The correct answer is actually to use object.unknown(true). const schema = Joi.object().keys({ a: Joi.string().required(), b: Joi.string().required() }).unknown(true);
The correct answer is actually to use object.unknown(true). const schema = Joi.object().keys({ a: Joi.string().required(), b: Joi.string().required() }).unknown(true);
replacing ordered with items will work. let Joi = require(‘joi’) let service = Joi.object().keys({ serviceName: Joi.string().required(), }) let services = Joi.array().items(service) let test = Joi.validate( [{ serviceName: ‘service1’ }, { serviceName: ‘service2’ }], services, ) For reference click here
Original answer: The current way (I personally find it better) is to use .messages() (or .prefs({messages})). const Joi = require(‘@hapi/joi’); const joiSchema = Joi.object({ a: Joi.string() .min(2) .max(10) .required() .messages({ ‘string.base’: `”a” should be a type of ‘text’`, ‘string.empty’: `”a” cannot be an empty field`, ‘string.min’: `”a” should have a minimum length of {#limit}`, ‘any.required’: … Read more
You can use valid. const schema = Joi.object().keys({ type: Joi.string().valid(‘ios’, ‘android’), }); const myObj = { type: ‘none’ }; const result = Joi.validate(myObj, schema); console.log(result); This gives an error ValidationError: child “type” fails because [“type” must be one of [ios, android]]
You can also use valid like const schema = joi.object().keys({ query: joi.object().keys({ // allow only apple and banana id: joi.string().valid(‘apple’,’banana’).required(), }).required(), }) Reference: https://github.com/hapijs/joi/blob/v13.1.2/API.md#anyvalidvalue—aliases-only-equal
Joi.array().items() accepts another Joi schema to use against the array elements. So an array of strings is this easy: Joi.array().items(Joi.string()) Same for an array of objects; just pass an object schema to items(): Joi.array().items(Joi.object({ // Object schema }))