Возможно, все, что вам нужно сделать, это пользовательская проверка , как в примере ниже.
ВЕРСИЯ 16.1.8 или выше
'use strict';
const Joi = require('@hapi/joi');
const customValidation = function (value, helpers) {
const validConcatenations = [
"1111:aaa", "111123:bbb", "12312:aab", "21323:zzzs"];
if (!validConcatenations.includes(`${value.file}:${value.extension}`)) {
throw Error(`Wrong concatenation ${value.file}:${value.extension}`)
}
return value;
};
const schema = Joi.object().keys({
file: Joi.string().required(),
extension: Joi.string().empty().required(),
}).custom(customValidation);
const wrongData = { file: '123654', extension: 'bbb' };
const niceData = { file: '1111', extension: 'aaa' };
console.log(schema.validate(wrongData));
console.log(schema.validate(niceData));
Выходы:
{ value: { file: '123654', extension: 'bbb' },
error:
{ ValidationError: "value" failed custom validation because Wrong concatenation 123654:bbb
_original: { file: '123654', extension: 'bbb' },
details: [ [Object] ] } }
{ value: { file: '1111', extension: 'aaa' } }
Глядя на документы , возможно сделать следующее решение начиная с версии 12.1.0
ВЕРСИЯ 12.1.0 или выше
'use strict';
const _Joi = require('@hapi/joi');
const custom = {
base: _Joi.object(),
name: 'custom',
language: {
concatenation: 'is a invalid concatenation',
},
rules: [
{
name: 'concatenation',
validate(params, value, state, options) {
const validConcatenations = [
"1111:aaa", "111123:bbb", "12312:aab", "21323:zzzs"];
if (!validConcatenations.includes(`${value.file}:${value.extension}`)) {
return this.createError('custom.concatenation', {v: value}, state, options);
}
return value;
}
}
]
};
const Joi = _Joi.extend(custom);
const schema = Joi.custom().keys({
file: Joi.string().required(),
extension: Joi.string().empty().required(),
}).concatenation();
const wrongData = { file: '123654', extension: 'bbb' };
const niceData = { file: '1111', extension: 'aaa' };
console.log(schema.validate(wrongData));
console.log(schema.validate(niceData));
Выходы:
{ error:
{ ValidationError: "value" is a invalid concatenation
at Object.exports.process (/tmp/test/node_modules/@hapi/joi/lib/errors.js:202:19)
at type._validateWithOptions (/tmp/test/node_modules/@hapi/joi/lib/types/any/index.js:762:31)
at type.validate (/tmp/test/node_modules/@hapi/joi/lib/types/any/index.js:796:21)
at Object.<anonymous> (/tmp/test/index.js:36:20)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Function.Module.runMain (module.js:694:10)
isJoi: true,
name: 'ValidationError',
details: [ [Object] ],
_object: { file: '123654', extension: 'bbb' },
annotate: [Function] },
value: { file: '123654', extension: 'bbb' },
then: [Function: then],
catch: [Function: catch] }
{ error: null,
value: { file: '1111', extension: 'aaa' },
then: [Function: then],
catch: [Function: catch] }