Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joi - make everything required by default?

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?

like image 918
john maccarthy Avatar asked May 02 '19 09:05

john maccarthy


People also ask

Is Joi required by default?

Most used joi functionsAll keys are optional by default.

Is not allowed to be empty in Joi?

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.

Can I use Joi in frontend?

I would strongly recommend using joi on the frontend now as you can share schemas between frontend and backend, which is really fantastic.


1 Answers

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();
like image 60
FINDarkside Avatar answered Sep 22 '22 04:09

FINDarkside