• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

502
Vistas
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 3 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

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 3 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda