1

I have an array that looks something like this

  settings: [
    { key: 'maxImageSize', value: '512' },
    { key: 'maxFileSize', value: '2048' },
    { key: 'searchResultsLimit', value: '10' },
  ]

I would like to validate the value of each key before saving them to a database.

Example: searchResultsLimit should be greater than 1 but never exceed 20.

I am using Objection.js and express-validator.

Thanks.

porone
  • 71
  • 1
  • 5

1 Answers1

0

Here's a function that returns a boolean based on whether the array is valid or invalid.


function myValidate(settings) {
  try {
    settings.map((setting) => {
      if (validator.toInt(setting.value) <= 1 || validator.toInt(setting.value) >= 20) {
        console.log(setting.value);
        throw new Error("Invalid");
      }
    });
  } catch (e) {
    console.log(e.message);
    return false;
  }
  return true;
}

Turns out validator.js does not provide a validator to check if a number is in range. Check https://github.com/validatorjs/validator.js/issues/330 for details.

In case you want to just ignore the items that are invalid, you can use the filter method instead to get the items in the required range.