[英]Joi validation schema - two fields must not have the same value
Assume I have the following schema:假设我有以下架构:
var schema = {
fieldOne: Joi.string().required(),
fieldTwo: Joi.string().required()
};
Is it possible to set a validation rule that checks if both fields have different values?是否可以设置验证规则来检查两个字段是否具有不同的值?
Yes it is. 是的。 You do this by making use of
Joi.ref
and Joi.invalid
(aliased to Joi.disallow
). 你可以通过使用
Joi.ref
和Joi.invalid
(别名为Joi.disallow
)来实现这Joi.disallow
。 For your particular example, it would be: 对于您的特定示例,它将是:
var assert = require('assert');
var Joi = require('joi');
var schema = Joi.object().keys({
fieldOne: Joi.string().required(),
fieldTwo: Joi.string().disallow(Joi.ref('fieldOne')).required()
});
And testing it yields us what we would expect: 测试它会让我们得到我们期望的结果:
assert.ok(Joi.validate(4, schema).error !== null);
assert.ok(Joi.validate({ fieldOne: 'a', fieldTwo: 'a' }, schema).error !== null);
assert.ok(Joi.validate({ fieldOne: 'a', fieldTwo: 'b' }, schema).error === null);
It works by referencing fieldOne
in our definition of fieldTwo
and disallowing the same value. 它的工作原理是在
fieldOne
的定义中fieldTwo
并禁止相同的值。
Unfortunately, I'm not sure that a direct validation for different values exists, but you can try to use array#unique()
instead: 不幸的是,我不确定是否存在对不同值的直接验证,但您可以尝试使用
array#unique()
代替:
var schema = {
fieldOne: Joi.string().required(),
fieldTwo: Joi.string().required(),
fieldOneAndTwo: Joi.array().unique()
};
and set fieldOneAndTwo = [fieldOne, fieldTwo]
before the validation. 并在验证之前设置
fieldOneAndTwo = [fieldOne, fieldTwo]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.