【问题标题】:Joi how to validate one of two field should not be emptyJoi如何验证两个字段之一不应为空
【发布时间】:2018-05-30 12:09:27
【问题描述】:

我有以下验证架构和示例数据。

var schema = Joi.alternatives().try(
  Joi.object().keys({
    searchTerm: Joi.string().trim().min(3).label('Search Term').options({ language: { any: { empty: 'should not be empty' } } }),
    location: Joi.string().allow(''),
    searchType: Joi.string().valid('people')
  }),
  Joi.object().keys({
    searchTerm: Joi.string().allow(''),
    location: Joi.string().trim().min(3).label('Location').options({ language: { any: { empty: 'should not be empty' } } }),
    searchType: Joi.string().valid('people')
  })
);

样本数据是:

{searchTerm: "", searchType: "people", location: ""}

不应通过并显示消息Please enter either search term or location. Make sure it contains 3 characters at least

{searchTerm: "as", searchType: "people", location: ""} 

不应通过并显示消息Search term must contain 3 characters at least

{searchTerm: "test", searchType: "people", location: ""}  // Should pass

我的验证模式在失败情况下显示两条消息

【问题讨论】:

    标签: node.js validation joi


    【解决方案1】:

    您可以将您的 joi 架构简化为此

    const schema = Joi.object().keys({
      searchTerm: Joi.string().trim().min(3),
      location: Joi.string().allow(''),
      searchType: Joi.string().valid('people'),
    }).or('searchTerm', 'location').error(new Error('Please enter either search term or location. Make sure it contains 3 characters at least'));
    

    但是,这不符合您的第二个条件(Search term must contain 3 characters at least),因为只能有一条错误消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-06
      • 1970-01-01
      • 2017-01-22
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      相关资源
      最近更新 更多