简体   繁体   English

JOI : 允许数组中的空值

[英]JOI :allow null values in array

I am trying to add a validation for array in a POST request我正在尝试在 POST 请求中添加对数组的验证

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 ?你能告诉我如何做到这一点吗?

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);

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()

非常简短的回答是:

name: Joi.string().allow(null)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM