Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

728
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!