我有以下验证架构和示例数据。
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
我的验证架构在失败情况下显示两条消息
答案 0 :(得分:0)
您可以将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
),因为只能有一条错误消息。