hapijs / hapijs/joi

How to throw warning for optional field?

Open
#2,886 1 comment 1 reaction 0 assignees View on GitHub
support
Dominant language
JavaScript
Stars
21.2k
Forks
1.5k
Avg merge
4h 57m
Merged PRs (30d)
14

Description

#### 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?
```js
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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.