Saturday, 22 April 2017

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()
        }
    }
};



via Solly

No comments:

Post a Comment