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()
}
}
};
As commented on the question, Joi.object()
will still work with a JSON
string, Joi.array()
works too.
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.