23

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 ?

user1110790
  • 787
  • 2
  • 8
  • 27

3 Answers3

44

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);
Cuthbert
  • 2,908
  • 5
  • 33
  • 60
  • Thank you :), this is perfect – user1110790 Jan 11 '17 at 20:18
  • I apologize this isn't perfectly on topic but I've searched for a while without an example and this is super close. I have an array of values but when I pass only 1 value in I get an error `"query.fields must be an array"` so Joi isn't converting the single item to an array before validating. If I pass two or more it passes validation. So I can't seem to get an array with one value in it: `fields: Joi.array().items(Joi.string().valid("val1", "valu2"))` Any idea here? – fIwJlxSzApHEZIl Jul 21 '20 at 03:08
4

the very short answer is:

name: Joi.string().allow(null)
B.Habibzadeh
  • 490
  • 6
  • 10
2

I know what i'm posting is not what you are looking for, but as i was ran into similar type of problem.

so my problem was: I do not want to allow empty array in my object

my solution:

// if you have array of numbers

key: joi.array().items(joi.number().required()).strict().required()

// if you have array of strings

key: joi.array().items(joi.string().required()).strict().required()
SefaUn
  • 824
  • 1
  • 7
  • 23
Subham kuswa
  • 356
  • 4
  • 12