简体   繁体   English

使用 Joi 浏览器进行异或验证

[英]XOR validation using Joi-browser

I am using joi-browser 13.4.0.我正在使用 joi 浏览器 13.4.0。 In order to generate error message for each input field I am trying to validate fields using.required() like so:为了为每个输入字段生成错误消息,我尝试使用.required() 验证字段,如下所示:


  config = {
    input1: Joi.string()
      .empty("")
      .required(),
    input2: Joi.string()
      .empty("")
      .required()
  };

  schema = Joi.object(this.config).xor("input1", "input2");

But this example is invalid because when input1 or input2 is set to.required(), .xor() function is being ignored.但此示例无效,因为当 input1 或 input2 设置为 .required() 时,.xor() function 将被忽略。 Is there any other way to implement XOR validation without using.xor() method?有没有其他方法可以在不使用.xor() 方法的情况下实现 XOR 验证?

Thanks.谢谢。

You don't need required() if you're using xor :如果您使用的是xor ,则不需要required()

config = {
  input1: Joi.string().empty(""),
  input2: Joi.string().empty("")
};

schema = Joi.object(config).xor("input1", "input2");

In fact, using required() like that would never validate.事实上,像这样使用required()永远不会验证。 You'd get one of the following error messages:您会收到以下错误消息之一:

ValidationError: child "input1" fails because ["input1" is required]

or或者

ValidationError: "value" contains a conflict between exclusive peers [input1, input2]

Use object.length()使用object.length()

Is there any other way to implement XOR validation without using.xor() method?有没有其他方法可以在不使用.xor() 方法的情况下实现 XOR 验证?

Yes, you could for example use the object().length() property to limit the keys in an object to 1 .是的,例如,您可以使用object().length()属性将 object 中的键限制为1

const Joi = require('joi-browser')

const schema = Joi.object().keys({
  input1: Joi.string().empty(''),
  input2: Joi.string().empty('')
}).required().length(1);

const value = {
  input1: "input1",
};

// this will fail
// const value = {};

// this will fail too
// const value = {
//   input1: 'input1',
//   input2: 'input2',
// };

const result = Joi.validate(value, schema);
console.log(JSON.stringify(result.error, null, 2));


Be careful当心

Don't forget to add required() to the parent object, otherwise it is possible to pass undefined to the validation function!不要忘记将required()添加到父 object 中,否则有可能将undefined传递给验证函数!

Without required() on the parent it is possible that a simple undefined will pass the validation:如果父级上没有required() ,则简单的undefined可能会通过验证:

const Joi = require('joi-browser')

const schema = Joi.object().keys({
  input1: Joi.string().empty(''),
  input2: Joi.string().empty('')
}).length(1); // no required()

const value = undefined; // this will pass validation

const result = Joi.validate(value, schema);
console.log(JSON.stringify(result.error, null, 2));

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

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