TL;DR:
const Joi = require('joi').extend(joi => ({
base: joi.array(),
coerce: (value, helpers) => ({
value: value.split ? value.split('|') : value,
}),
type: 'versionArray',
}))
.extendfunction signature has changed,因为该评论已写; name 属性已被移除,CoerceFunction 应返回一个以 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(...) 函数来验证返回数组中的每个字符串:
> 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] ] } }