JOI :allow null values in array

user1110790 picture user1110790 · Jan 4, 2017 · Viewed 12.1k times · Source

I am trying to add a validation for array in a POST request

Joi.array().items(Joi.string()).single().optional()

I need to allow null values in the payload. Can you please tell me how this can be done ?

Answer

Cuthbert picture Cuthbert · Jan 9, 2017

If you want to allow the array to be null use:

Joi.array().items(Joi.string()).allow(null);

If you want to allow null or whitespace strings inside the array use:

Joi.array().items(Joi.string().allow(null).allow(''));

Example:

const Joi = require('joi');

var schema = Joi.array().items(Joi.string()).allow(null);

var arr = null;

var result = Joi.validate(arr, schema); 

console.log(result); // {error: null}

arr = ['1', '2'];

result = Joi.validate(arr, schema);

console.log(result); // {error: null}


var insideSchema = Joi.array().items(Joi.string().allow(null).allow(''));

var insideResult = Joi.validate(['1', null, '2'], insideSchema);

console.log(insideResult);