Parameter validation I want to ensure that the array must not be empty in any cost so that i want to validate the array
imgList= [ { "fileType": "png", "fileContent": "base64" }, { "fileType": "png", "fileContent": "base64" } ] I want to validate both key and value is present or not (it should not be empty)
eg: filetype is missing
{
"fileContent": "base64"
},
eg2: value is missing
{
"fileType": "",
"fileContent": "base64"
},
Code which i have tired is
body.imgList.forEach((item) => {
var key,
count = 0;
for (let [key, value] of Object.entries(item)) {
if (item.hasOwnProperty(key) && !!value) {
count ;
}
}
var objectLenght = count;
if (objectLenght != 2) {
return cb({"status_code":400,"status":"Pass all the required fields"});
}
});
When I try this worked is died and image are uploaded with out type in s3
CodePudding user response:
Javascript's truthy
/ falsy
system takes care of this for you. If the key does not exist you will get undefined
when attempting to access it, which is falsy
. An empty string is also a falsy
value.
function validate(data) {
if (!data || !data.length) return false;
for (const item of data) {
if (!item || !item.fileType || !item.fileContent) return false;
}
return true;
}
if (validate(body.imgList)) return cb({ status_code: 400, status: 'Pass all the required fields' });;
More info on falsy
: https://developer.mozilla.org/en-US/docs/Glossary/Falsy
CodePudding user response:
I hope this works, you can use isOkay function to verify if the array is valid
const isOkay = (arr)=> {
let okay = true;
for(let entry of arr){
if(!entry.hasOwnProperty('fileType') || !entry['fileType'] || !entry.hasOwnProperty('fileContent') || !entry['fileContent']){
okay = false;
break;
}
}
return okay;
}