繁体   English   中英

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

工作演示

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;
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM