Joi 验证数组中的总和

Joi validate Sum across an Array

我想验证给定的 JSON ,expenditure 的约束不得超过 credit

{
  "expenditure": {
    "house": 2,
    "electricity": 1,
    "phone": 12
  },
  "credit": 6
}
const Joi = require("joi");

const schema = Joi.object({

    expenditure: Joi.object({
        house: Joi.number().integer().min(0).max(5).optional(),
        electricity: Joi.number().integer().min(0).max(5).optional(),
        phone: Joi.number().integer().min(0).max(5).optional()
    }),

    credit: Joi.number().integer().min(0).max(15).greater(
        Joi.ref('expenditure', {"adjust": expenditure => {
            return expenditure.house + expenditure.electricity + expenditure.phone;
        }})
    )
});

上面的代码可以很好地限制在一个对象范围内,但我需要验证这种类型的东西

[
    {
        "phone_allowance": 12
    },
    {
        "phone_allowance": 10
    },
]

为了确保数组中所有 phone_allowance 的总和永远不会超过某个给定值,比如 50

您可以使用custom()

https://github.com/sideway/joi/blob/master/API.md#anycustommethod-description

Working Demo

var schema = Joi.array().items(
  Joi.object({
    phone_allowance: Joi.number()
  })
).custom((value, helpers) => {
  var total = value.reduce((a, b) => a + b.phone_allowance, 0)

  if (total > 5) {
    return helpers.error('any.invalid');
  }

  return value;
});