Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

732
Visualizações
How to validate if body parameter in Express Nodejs string can be converted to JSON using express-validation and joi

I am creating a function that accepts a post request. The post request also contains a JSON object converted to a String. On the backend, I need to validate if this string can indeed be parsed into JSON and only then proceed. There is the routing function:

var express = require('express');
var validate = require('express-validator');

var hotelController = require('../controllers/hotel-controller');
var hotelValidation = require('../validations/hotel-validation');

var router = express.Router();


router.route('/create')
    .post(validate(hotelValidation.createHotel), 
hotelController.create);

Here is the validation object:

var Joi = require('joi');

module.exports = {
    createHotel: {
        body: {
            //NEED TO CHECK IF THE BELOW FIELD 
            //CAN BE CONVERTED TO JSON FROM STRING
            data: Joi.string().required()
        }
    }
};
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

As commented on the question, Joi.object() will still work with a JSON string, Joi.array() works too.

It's documented in the API

Generates a schema object that matches an object data type (as well as JSON strings that parsed into objects).

For example, given the schema:

Joi.object().keys({
  body: Joi.object().keys({
    data: Joi.object(),
    array: Joi.array()
  })
})

A valid payload can be:

{
  body: {
    data: '{"json": true, "foo": "bar"}',
    array: '[1, 2, 3, "hello", 4, "world"]'
  }
}

The above example can be demoed here, just paste the schema and example data in.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda