how to accept null or empty field with Celebrate js middleware

Asked

Viewed 164 times

-1

Good morning, I am validating the data on a backend route and need a null or empty accepted field, so I used the following code:

// Rota para postar arte individual
router.post('/postarArte',
    verificarToken,  

    // upload
    multer(multerConfig).single('file'),

    // validação de dados
    celebrate({
        [Segments.BODY]: Joi.object().keys({
            titulo: Joi.string().required().max(30),
            desc: Joi.string().allow(null).max(500),
            tipo: Joi.string().required()
        })
    }),     

    // inserção no banco de dados
    postarArte
);

I am sending the following Multipart form for testing:

arquivo: [File]
desc: "" // Preciso que esse campo aceite vazio
tipo: "ILLUSTRATION"
titulo: "asdasd"

and always returns me "status 400 (Bad Request)", there is some other way to do this?

2 answers

0


I managed to solve with the following code:

...
desc: Joi.string().allow(null, '').max(500),
...

-1

I don’t know which version of Node you use, but from version 14 there was the implementation of Operator of null coalescence expressed by ??. I believe this will serve your case, putting validation in the field desc ?? valorDesejado.

Unlike the ||, the ?? will consider valid any value as long as it is not valid null or undefined.

Null coalescence

"" ?? "teste" // retorna ""

false ?? "teste" // retorna false

undefinded ?? "teste" // retorna "teste"

null ?? "teste" // retorna "teste"

Operator "OR"

"" || "teste" // retorna "teste"

false || "teste" // retorna "teste"

undefinded || "teste" // retorna "teste"

null || "teste" // retorna "teste"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.