node.js - Validate REST parameters using Joi in Nodejs -
i trying validate request in hapi node server using joi package. validation working correctly expected. struggling find way return error if there no parameters passed. if there no parameters passed succeeds. there way modify response being sent?
var hapi = require('hapi'); var joi = require('joi'); var server = module.exports = new hapi.server(); server.connection({ host : process.env.host, port : 3000 }); server.route({ method: 'get', path: '/test', config: { validate: { query: { a: joi.string().regex(/[0-9a-f]{8}-[0-9a-f]{4}/), b: joi.string(), c: joi.string(), d: joi.string(), e: joi.string() } } }, handler: function(req, reply) { reply('i beautiful butterfly'); } }); server.start();
you can use object.or()
that:
config: { validate: { query: joi.object().keys({ a: joi.string(), b: joi.string(), c: joi.string(), d: joi.string(), e: joi.string() }).or('a', 'b', 'c', 'd', 'e') } },
when none of query parameters specified, following response returned:
{ statuscode: 400, error: 'bad request', message: '"value" must contain @ least 1 of [a, b, c, d, e]', validation: { source: 'query', keys: [ 'value' ] } }
to modify response, can use custom handler failaction()
:
config: { validate: { query: joi.object().keys({ a: joi.string(), b: joi.string(), c: joi.string(), d: joi.string(), e: joi.string() }).or('a', 'b', 'c', 'd', 'e'), failaction: function(request, reply, source, error) { return reply({ message: error.output.payload.message }); } } },
Comments
Post a Comment