使用Joi,要求两个字段之一不能为空

编程入门 行业动态 更新时间:2024-10-26 14:38:12
本文介绍了使用Joi,要求两个字段之一不能为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我有两个字段,我只想验证至少一个字段是一个非空字符串,但是当两个字段都是空字符串时都会失败.

If I have two fields, I'd just like to validate when at least one field is a non empty string, but fail when both fields are empty strings.

类似的事情无法验证

var schema = Joi.object().keys({ a: Joi.string(), b: Joi.string() }).or('a', 'b');

根据进行验证

{a: 'aa', b: ''}

or条件仅测试键a或b的存在,但会测试a或b的条件是否为真. Joi.string()对于空字符串将失败.

The or condition only tests for the presence of either key a or b, but does test whether the condition for a or b is true. Joi.string() will fail for empty strings.

这里有一些测试用例可以证明

Here is gist with some test cases to demonstrate

requirebin/?gist=84c49d8b81025ce68cfb

推荐答案

以下代码对我有用.我使用替代方法是因为.or实际上正在测试密钥的存在性,而您真正想要的是一种替代方法,其中您允许一个密钥或另一个密钥为空.

Code below worked for me. I used alternatives because .or is really testing for the existence of keys and what you really wanted was an alternative where you would allow one key or the other to be empty.

var console = require("consoleit"); var Joi = require('joi'); var schema = Joi.alternatives().try( Joi.object().keys({ a: Joi.string().allow(''), b: Joi.string() }), Joi.object().keys({ a: Joi.string(), b: Joi.string().allow('') }) ); var tests = [ // both empty - should fail {a: '', b: ''}, // one not empty - should pass but is FAILING {a: 'aa', b: ''}, // both not empty - should pass {a: 'aa', b: 'bb'}, // one not empty, other key missing - should pass {a: 'aa'} ]; for(var i = 0; i < tests.length; i++) { console.log(i, Joi.validate(tests[i], schema)['error']); }

更多推荐

使用Joi,要求两个字段之一不能为空

本文发布于:2023-11-07 04:18:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565554.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   为空   两个   Joi

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!