const schema = Joi.object().keys({
age: Joi.number().min(18).error(new Error('Must be at least 18')),
});
const data = { age: 16 };
const { error, value } = schema.validate(data);
if (error) {
console.log(error.message); // Must be at least 18
}
Joi.extend(joi => ({
base: joi.type(),
name: 'string',
language: {
notContainsSubstring: 'does not contain the substring {{substring}}',
},
rules: [
{
name: 'notContainsSubstring',
params: {
substring: joi.string().required(),
},
validate(params, value, state, options) {
if (value.indexOf(params.substring) !== -1) {
return this.createError('string.notContainsSubstring', {
value,
substring: params.substring,
}, state, options);
}
return value;
},
},
],
}));
const schema = Joi.string().notContainsSubstring('bad');
const data = 'This is a good string';
const { error, value } = schema.validate(data);
if (error) {
console.log(error.message); // does not contain the substring bad
}