我有一个场景,我需要使用不同的正则表达式验证增值税号码,具体取决于它所在的国家/地区。因此,当字段language
为SE
时,我想在字段/^\d{6}-\d{4}$/
上使用此正则表达式company.vatNo
,但字段language
为NO
时我想使用这个/^\d{9}(MVA)?$/
..我想我可以和Joi一起去(),但它似乎根本不起作用。有谁知道我怎么能做到这一点?
这是我验证的路线:
module.exports = {
method: 'POST',
path: '/signup/{partner}',
handler: createPartner,
config: {
validate: {
payload: {
language: Joi.string().allow(config.supportedLanguages).required(),
company: {
vatNo: {
Joi
.when('language', {
is: 'SE',
then: Joi.string().regex(/^\d{6}-\d{4}$/).required()
})
.when('language', {
is: 'NO',
then: Joi.string().regex(/^\d{9}(MVA)?$/).required()
})
.when('language', {
is: 'FI',
then: Joi.string().regex(/^\d{7}-\d{1}$/).required()
})
}
}
}
}
}
由于
答案 0 :(得分:2)
Here's the solution. It seems like Joi doesn't recognize language
if vatNo
is inside another object. But this solved the problem:
language: Joi.any().valid(config.supportedLanguages).required(),
vatNo:
Joi.alternatives()
.when('language', {
is: Joi.string().regex(/^(SE)$/i),
then: Joi.string().regex(/^\d{6}-\d{4}$/).label('companyID')
})
.when('language', {
is: Joi.string().regex(/^(NO)$/i),
then: Joi.string().regex(/^\d{9}(MVA)?$/).label('companyID')
})
.when('language', {
is: Joi.string().regex(/^(FI)$/i),
then: Joi.string().regex(/^\d{7}-\d{1}$/).label('companyID')
}),