Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate array of objects using Joi?

I am getting an array of objects to backend, where each object contains a service name. The structure looks like below

[{"serviceName":"service1"}, {"serviceName":"service2"},..] 

when I get the array at backend, I want to validate that every object in the array has serviceName property.

I had written the following code, but even though I pass valid array, I am getting validation error.

var Joi = require('joi'); var service = Joi.object().keys({   serviceName: Joi.string().required() });  var services = Joi.array().ordered(service);  var test = Joi.validate([{serviceName:'service1'},{serviceName:'service2'}],services) 

For the above code, I am always getting the validation error with message

"value" at position 1 fails because array must contain at most 1 items 
like image 642
zakir Avatar asked Jun 10 '16 09:06

zakir


2 Answers

replacing ordered with items will work.

let Joi = require('joi') let service = Joi.object().keys({   serviceName: Joi.string().required(), })  let services = Joi.array().items(service)  let test = Joi.validate(   [{ serviceName: 'service1' }, { serviceName: 'service2' }],   services, ) 

For reference click here

like image 162
zakir Avatar answered Sep 28 '22 09:09

zakir


A basic/ clearer example is as follows. To validate a JSON request like this:

   {     "data": [             {         "keyword":"test",         "country_code":"de",         "language":"de",         "depth":1             }         ]     } 

Here is the Joi validation:

 seoPostBody: {     body: {       data: Joi.array()         .items({           keyword: Joi.string()             .required(),           country_code: Joi.string()             .required(),           language: Joi.string()             .required(),           depth: Joi.number()             .required(),         }),     },   }; 

This is what I am doing in NodeJs, might need some slight changes for other platforms

like image 36
sediq khan Avatar answered Sep 28 '22 09:09

sediq khan