Javascript 备选方案情况下的Joi验证

Javascript 备选方案情况下的Joi验证,javascript,json,node.js,validation,joi,Javascript,Json,Node.js,Validation,Joi,有一个对象有三个键 const abc = { customerId: '777', firstName: 'pqr'', lastName: 'xyz', }; 条件是,如果存在客户id,则可以忽略firstname和lastname。否则,它们应该是最大长度为20的字符串 const schema = Joi.object({ customerId: Joi.string(), firstName: Joi.alternatives().when('customerId

有一个对象有三个键

const abc = {
  customerId: '777',
  firstName: 'pqr'',
  lastName: 'xyz',
};
条件是,如果存在客户id,则可以忽略firstname和lastname。否则,它们应该是最大长度为20的字符串

const schema = Joi.object({
  customerId: Joi.string(),
  firstName: Joi.alternatives().when('customerId', {
    is: null,
    then: Joi.string(),
  }),
  lastName: Joi.alternatives().when('customerId', {
    is: null,
    then: Joi.string(),
  })
})
Joi.validate(abc, schema);
这里我得到了这个错误

错误:{ValidationError:“firstName”是不允许的 在Object.exports.process(/home/runner/node_modules/joi/lib/errors.js:


那么,这是如何实现的呢?

这是因为您的模式查找
firstname
,而您的对象具有
firstname
。请尝试不使用大写字母
N

const abc = {
   customerId: '777',
   firstname: 'pqr',
   lastname: 'xyz'
};

当时,应使用
而不是

下面是一个运行示例:

模式:

const schema = Joi.object({
  customerId: Joi.string(),
  firstName: Joi.string().max(20),
  lastName: Joi.string().max(20),
}).or('customerId', 'lastName')
  .or('customerId', 'firstName');

根据您的回答,可能是customer id和lastname,也可能是customerid和firstname。但是如果customerid不存在,那么firstname和lastname都应该存在。更正后会出现不同的错误。您能检查一下吗?@Aayushi