hapijs / joi

The most powerful data validation library for JS
Other
20.95k stars 1.51k forks source link

How to throw warning for optional field? #2886

Open MubashirWaheed opened 2 years ago

MubashirWaheed commented 2 years ago

Support plan

Context

How can we help?

Basically, I want to throw a warning if an optional field is empty. How can this be achieved?

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'}));

Birth year is an optional field and if it is empty how do I throw a warning?

Relevant question on StackOverflow: https://stackoverflow.com/questions/73415737/how-to-make-joi-warning-on-non-existant-property

Nargonath commented 2 years ago

I think if you use anySchema.warning() the warning will always be thrown so you don't have the conditional behaviour you're looking for. Have you tried using a custom validation for that: https://joi.dev/api/?v=17.7.0#anycustommethod-description?