How To Make Joi Warning On Non-Existant property

Viewed 47

How can I use Joi to throw a WARNING but not an ERROR if a particular element does not exist?

My Code:

const Joi = require('joi');

const schema = Joi.object({
    username: Joi.string()
        .alphanum()
        .min(3)
        .max(30)
        .required(),
    birth_year: Joi
        .number()
        .min(2000)
        .warn()
});

console.log({ error, warning, value } = schema.validate({ username: 'abc', birth_year: 1994 }));
console.log({ error, warning, value } = schema.validate({ username: 'abc'}));

I can successfully see a warning when the birth year does not have the minimum I require

'"birth_year" must be greater than or equal to 2000'

however, I also want to WARN if birth year does not exist.

Currently I do not get a warning or an error. If I add .required() to the birth year schema it will ERROR if birth year does not exist. I have tried making this:

birth_year: Joi
        .number()
        .min(2000)
        .warn()
        .required()
        .warn()

however this generates a runtime error because .warn() terminates the schema options. I also tried moving .required to be the second option, but again it errors, not warns.

0 Answers
Related