• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

503
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 3 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 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error