使用 JOI 验证分隔符分隔值
Validate delimiter separated values using JOI
我有一个用例,我需要验证一组由 | 分隔的值.
我遵循了 https://github.com/hapijs/joi/issues/570 但它抛出了一些错误。
有什么办法可以做到这一点?
示例- AA|BB|CC|DD
现在,我需要验证所有值(AA、BB、CC、DD)都是字符串。
我认为我不能使用正则表达式,因为它只会验证第一个值。
此外,我的代码中还有许多其他验证,所以我不想循环验证过程。
如果我不清楚,请告诉我。谢谢!
TL;DR:
const Joi = require('joi').extend(joi => ({
base: joi.array(),
coerce: (value, helpers) => ({
value: value.split ? value.split('|') : value,
}),
type: 'versionArray',
}))
.extend
function signature has changed 自该评论发表以来; name
属性 已被删除并且 CoerceFunction
应该 return 一个对象 value
作为 属性.
> Joi.versionArray().validate('AA|BB|CC|DD')
{ value: [ 'AA', 'BB', 'CC', 'DD' ] }
> Joi.versionArray().validate('AA|BB,CC|DD')
{ value: [ 'AA', 'BB,CC', 'DD' ] }
从这里开始,您可以使用 .items(...)
函数来验证 returned 数组中的每个字符串:
> const regex = new RegExp('^[a-zA-Z]+$') // every character must be a-z or A-Z
undefined
> Joi.versionArray().items(Joi.string().regex(regex)).validate('AA|BB|CC|DD')
{ value: [ 'AA', 'BB', 'CC', 'DD' ] }
> Joi.versionArray().items(Joi.string().regex(regex)).validate('AA|BB|CC|00')
{ value: [ 'AA', 'BB', 'CC', '00' ],
error:
{ ValidationError: "[3]" with value "00" fails to match the required pattern: /^[a-zA-Z]+$/ _original: 'AA|BB|CC|00', details: [ [Object] ] } }
> Joi.versionArray().items(Joi.string().regex(regex)).validate('AA|BB,CC|DD')
{ value: [ 'AA', 'BB,CC', 'DD' ],
error:
{ ValidationError: "[1]" with value "BB,CC" fails to match the required pattern: /^[a-zA-Z]+$/ _original: 'AA|BB,CC|DD', details: [ [Object] ] } }
我有一个用例,我需要验证一组由 | 分隔的值.
我遵循了 https://github.com/hapijs/joi/issues/570 但它抛出了一些错误。 有什么办法可以做到这一点?
示例- AA|BB|CC|DD
现在,我需要验证所有值(AA、BB、CC、DD)都是字符串。
我认为我不能使用正则表达式,因为它只会验证第一个值。
此外,我的代码中还有许多其他验证,所以我不想循环验证过程。
如果我不清楚,请告诉我。谢谢!
TL;DR:
const Joi = require('joi').extend(joi => ({
base: joi.array(),
coerce: (value, helpers) => ({
value: value.split ? value.split('|') : value,
}),
type: 'versionArray',
}))
.extend
function signature has changed 自该评论发表以来; name
属性 已被删除并且 CoerceFunction
应该 return 一个对象 value
作为 属性.
> Joi.versionArray().validate('AA|BB|CC|DD')
{ value: [ 'AA', 'BB', 'CC', 'DD' ] }
> Joi.versionArray().validate('AA|BB,CC|DD')
{ value: [ 'AA', 'BB,CC', 'DD' ] }
从这里开始,您可以使用 .items(...)
函数来验证 returned 数组中的每个字符串:
> const regex = new RegExp('^[a-zA-Z]+$') // every character must be a-z or A-Z
undefined
> Joi.versionArray().items(Joi.string().regex(regex)).validate('AA|BB|CC|DD')
{ value: [ 'AA', 'BB', 'CC', 'DD' ] }
> Joi.versionArray().items(Joi.string().regex(regex)).validate('AA|BB|CC|00')
{ value: [ 'AA', 'BB', 'CC', '00' ],
error:
{ ValidationError: "[3]" with value "00" fails to match the required pattern: /^[a-zA-Z]+$/ _original: 'AA|BB|CC|00', details: [ [Object] ] } }
> Joi.versionArray().items(Joi.string().regex(regex)).validate('AA|BB,CC|DD')
{ value: [ 'AA', 'BB,CC', 'DD' ],
error:
{ ValidationError: "[1]" with value "BB,CC" fails to match the required pattern: /^[a-zA-Z]+$/ _original: 'AA|BB,CC|DD', details: [ [Object] ] } }