如何根据查询值链接快速验证器?
How to chain express-validator based on query values?
我正在尝试根据传递给路由的查询值找到链式条件的解决方案。
Task1:
// if value for query A = noIdNeeeded, then i do not need to search for a second queryB
/endpoint?queryA=noIdNeeded
Task2:
// if value for query A = idNeeded, then i need to ensure second queryB exists
/endpoint?queryA=idNeeded&queryB=SomeId
我在为任务 2 写入参数时遇到问题。
对于任务 1,我使用了这个逻辑并且工作正常[query('page').exists().notEmpty().isIn(seoPageTypes),]
到目前为止,我已经看到我们可能会使用一个 if 子句 (link),但是由于缺乏示例且之前没有经验,实现这个一直是一个挑战。
如果有人可以指导如何正确执行此操作或任何提示,我们将不胜感激。
确保您安装了新版本的 express-validator。
以下应该完成你的工作。
query('queryA').exists().notEmpty().isIn(seoPageTypes),
query('queryB')
.if(query('queryA').equals('idNeeded'))
.exists().notEmpty().withMessage('queryB must exist'),
另一种方法是使用 custom validator
query('queryA').exists().notEmpty().isIn(seoPageTypes)
.custom((value, {req}) => {
if (value === "idNeeded" && !req.query.queryB) {
throw new Error('queryB must exist');
}
return true;
}),
使用更适合你的:)
我正在尝试根据传递给路由的查询值找到链式条件的解决方案。
Task1:
// if value for query A = noIdNeeeded, then i do not need to search for a second queryB
/endpoint?queryA=noIdNeeded
Task2:
// if value for query A = idNeeded, then i need to ensure second queryB exists
/endpoint?queryA=idNeeded&queryB=SomeId
我在为任务 2 写入参数时遇到问题。
对于任务 1,我使用了这个逻辑并且工作正常[query('page').exists().notEmpty().isIn(seoPageTypes),]
到目前为止,我已经看到我们可能会使用一个 if 子句 (link),但是由于缺乏示例且之前没有经验,实现这个一直是一个挑战。
如果有人可以指导如何正确执行此操作或任何提示,我们将不胜感激。
确保您安装了新版本的 express-validator。
以下应该完成你的工作。
query('queryA').exists().notEmpty().isIn(seoPageTypes),
query('queryB')
.if(query('queryA').equals('idNeeded'))
.exists().notEmpty().withMessage('queryB must exist'),
另一种方法是使用 custom validator
query('queryA').exists().notEmpty().isIn(seoPageTypes)
.custom((value, {req}) => {
if (value === "idNeeded" && !req.query.queryB) {
throw new Error('queryB must exist');
}
return true;
}),
使用更适合你的:)