Validating an array's length against another array's length using joi

自作多情 提交于 2019-12-24 01:03:43

问题


Is there a way to validate that two arrays need to have the same length using joi?

Here's an example:

Joi.object().keys({
  firstNames: Joi.array().items(Joi.string()).single(),
  lastNames: Joi.array().items(Joi.string()).single(),
});

If that was to work, it should also match both array's length so no firstName lacks a lastName.

Thanks for the help!


回答1:


There certainly is, take a look at .assert(). You can use it to compare the values or attributes of two properties in your object.

For your example you can do this:

Joi.object().keys({
  firstNames: Joi.array().items(Joi.string()).single(),
  lastNames: Joi.array().items(Joi.string()).single(),
}).assert('firstNames.length', Joi.ref('lastNames.length'));

You can also optionally provide a more helpful error message as the third parameter of .assert().



来源:https://stackoverflow.com/questions/53127060/validating-an-arrays-length-against-another-arrays-length-using-joi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!