【问题标题】:Express Validator: Custom validation with asynchronous functionsExpress Validator:使用异步函数的自定义验证
【发布时间】:2022-01-02 06:32:40
【问题描述】:

我目前正在尝试使用 express-validator 验证 Express 中的一些输入。我知道通常将它作为单独的中间件传递到路由中,但我需要访问 res 对象,所以我必须按照您在下面看到的方式编写它。

我正在努力解决的部分是custom 验证器。我希望它调用异步函数store.todoListTitleExists(title) 来查询数据库并检查标题是否已经存在。如果标题不存在,我的意图是保存一条错误消息,稍后我可以将其显示为 Flash 消息。

目前,此代码不起作用。我查看了文档,但我似乎无法弄清楚如何使这个自定义验证器 + 错误消息正常工作,因为它调用了一个异步函数。任何帮助将不胜感激。

谢谢!

app.post("/lists/:todoListId/edit", 
    (req, res) => {
    let store = res.locals.store;
    let todoListId = req.params.todoListId;
    let title = req.body.todoListTitle;

    await body('todoListTitle')
          .trim()
          .isLength({ min: 1 })
          .withMessage("The list title is required.")
          .isLength({ max: 100 })
          .withMessage("The list title cannot be over 100 characters")
          .custom(store.todoListTitleExists(title).then(titleExists => {
            if(titleExists) return Promise.reject('Title already exists');
          }))

【问题讨论】:

  • 更好的方法是使用可以拦截请求的中间件,然后你可以做其他任务......就像app.use(...)

标签: javascript express async-await es6-promise express-validator


【解决方案1】:

试试这个

body("feildName", "Feild must be selected")
.custom(value=> {

    titleExists=await store.todoListTitleExists(value)
    if(titleExists){
    Promise.reject('title exists')
    }
    return true


    return true

}),

【讨论】:

    【解决方案2】:

    Express-validator 旨在清理和验证客户端和服务器之间发送的数据。为了以可扩展的方式处理此问题,我建议使用一个文件来处理您所有网站的发布请求(例如routes.js)。

    这是一个示例自定义路由器,如果验证失败,则会显示错误消息:

    body("feildName", "Feild must be selected")
        .custom(val => {
    
            if (val.feildName == "Select...") return false
    
            return true
    
        }),
    

    一旦您将所有路由隔离到特定文件,您就可以像下面的示例一样添加参数,以便与页面一起提供错误消息(我个人使用 ejs 模板,因此这些错误消息使用以下代码显示:

    **controller.js**
        const errors = validationResult(req);
        const {
            body
        } = req;
    
        if (!errors.isEmpty()) {
            return res.render('index', {
                error: errors.array()[0].msg
            });
        }
    
        res.render("index");
    
    **index.ejs**
    <div class="error">
            <% if(typeof error !== 'undefined'){ %>
                  <div class="err-msg"><%= error %></div>
            <% } %>
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-05
      • 2015-12-04
      • 2012-09-14
      • 1970-01-01
      • 2013-07-11
      相关资源
      最近更新 更多