Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JOI :allow null values in array

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 ?

like image 951
user1110790 Avatar asked Jan 04 '17 17:01

user1110790


People also ask

How do I allow an empty string in Joi validation?

That's why you explicitly have to allow empty strings like this: Joi. string(). allow('') .


2 Answers

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);
like image 163
Cuthbert Avatar answered Sep 20 '22 11:09

Cuthbert


the very short answer is:

name: Joi.string().allow(null)
like image 30
B.Habibzadeh Avatar answered Sep 19 '22 11:09

B.Habibzadeh