joi
joi copied to clipboard
How to throw warning for optional field?
trafficstars
Support plan
- is this issue currently blocking your project? (yes/no): no
- is this issue affecting a production system? (yes/no): no
Context
- node version: v18.12.1
- module version: "^17.7.0"
- environment (e.g. node, browser, native): node
- used with (e.g. hapi application, another framework, standalone, ...): standalone
- any other relevant information:
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
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?