使用 joi 检查输入变量是字符串还是数组
check if an input variable is string or array using joi
我有一个 api,在过去的开发中会接收逗号分隔的字符串作为有效输入,并使用以下内容作为验证器:
Joi.string()
但现在我想使用此处提到的字符串数组实现相同的变量https://github.com/glennjones/hapi-swagger/issues/119。所以新的检查将是:
Joi.array().items(Joi.string())
但我不想破坏代码的向后兼容性。有没有办法检查变量的两个条件?
我是 Joi 的新手,如有任何帮助或指导,我们将不胜感激。提前致谢。
看看 .alternatives().try()
,它支持单个字段的多个模式。
例如:
Joi.alternatives().try(Joi.array().items(Joi.string()), Joi.string())
这将验证字符串数组和纯字符串,但是我相信您知道,您仍然需要服务器端逻辑来检查值的格式,以便您可以正确处理它。
您可以使用 alternatives.try 或 shorthand [schema1, schema2]
const Joi = require('joi');
const schema1 = {
param: Joi.alternatives().try(Joi.array().items(Joi.string()), Joi.string())
};
const result1 = Joi.validate({param: 'str1,str2'}, schema1);
console.log(result1.error); // null
const result2 = Joi.validate({param: ['str1', 'str2']}, schema1);
console.log(result2.error); // null
const schema2 = {
param: [Joi.array().items(Joi.string()), Joi.string()]
};
const result3 = Joi.validate({param: 'str1,str2'}, schema2);
console.log(result3.error); // null
const result4 = Joi.validate({param: ['str1', 'str2']}, schema2);
console.log(result4.error); // null
我有一个 api,在过去的开发中会接收逗号分隔的字符串作为有效输入,并使用以下内容作为验证器:
Joi.string()
但现在我想使用此处提到的字符串数组实现相同的变量https://github.com/glennjones/hapi-swagger/issues/119。所以新的检查将是:
Joi.array().items(Joi.string())
但我不想破坏代码的向后兼容性。有没有办法检查变量的两个条件?
我是 Joi 的新手,如有任何帮助或指导,我们将不胜感激。提前致谢。
看看 .alternatives().try()
,它支持单个字段的多个模式。
例如:
Joi.alternatives().try(Joi.array().items(Joi.string()), Joi.string())
这将验证字符串数组和纯字符串,但是我相信您知道,您仍然需要服务器端逻辑来检查值的格式,以便您可以正确处理它。
您可以使用 alternatives.try 或 shorthand [schema1, schema2]
const Joi = require('joi');
const schema1 = {
param: Joi.alternatives().try(Joi.array().items(Joi.string()), Joi.string())
};
const result1 = Joi.validate({param: 'str1,str2'}, schema1);
console.log(result1.error); // null
const result2 = Joi.validate({param: ['str1', 'str2']}, schema1);
console.log(result2.error); // null
const schema2 = {
param: [Joi.array().items(Joi.string()), Joi.string()]
};
const result3 = Joi.validate({param: 'str1,str2'}, schema2);
console.log(result3.error); // null
const result4 = Joi.validate({param: ['str1', 'str2']}, schema2);
console.log(result4.error); // null