I'm building out a Node/Express API and using Joi for validation. It's a great package and has been incredibly useful. However, we're getting tired of doing things like:
const mySchema = joi.object({
thing1: joi.string().required(),
thing2: joi.string().required(),
thing3: joi.string().required(),
thing4: joi.string().required(),
thing5: joi.string().required(),
}).required();
We'd like everything to be required by default, and manually call .optional
to override that. In fact this seems a sensible default - but leaving that aside for now.
Is there a way to achieve this?
Most used joi functionsAll keys are optional by default.
Well, turns out that Joi doesn't allow empty strings when you put Joi. string() - even though I didn't specifically make it a required field and all validations are optional by default.
I would strongly recommend using joi on the frontend now as you can share schemas between frontend and backend, which is really fantastic.
You can use presence
option to make fields required by default. Example:
const mySchema = joi.object({
thing1: joi.string(),
thing2: joi.string(),
thing3: joi.string(),
thing4: joi.string(),
thing5: joi.string(),
}).options({ presence: 'required' }).required();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With