【问题标题】:Can express-form validate an input type of 'file' to be required?express-form 可以验证需要的“文件”输入类型吗?
【发布时间】:2012-06-16 11:13:02
【问题描述】:

我正在使用express-formhttps://github.com/dandean/express-form

它是否能够验证file 类型的输入?我特别想require有人上传文件。

为 Linus 编辑 :)

我试过了: field("pdf").required("pdf", "You must select a file to upload.")

问题是,这是找req.body.pdf而不是req.files.pdf,所以它总是认为验证失败。

编辑/工作代码:根据 Linus 的回答,我做了什么让它工作。

我不仅需要配置dataSources 参数,还需要检查字段的size 属性,因为仅在字段上执行required 还不够好,因为即使文件输入为空,它仍然存在(元数据等)。因此,我使用自定义验证函数确保pdf.size 大于0。在我的代码中,我还检查是否有title。我把它留在这里,以防有人想知道如何将多个验证串在一起。

var form = require('express-form')
  .configure({dataSources: ['body', 'files', 'query', 'params']});

form(
  field("pdf.size").custom(function(value) {
    if (value <= "0") {
      throw new Error("You must select a file to upload.");
    }
  })
 , field("title").trim().required("title", "Please enter a title for your PDF."))

【问题讨论】:

  • @LinusGThiel 好点,添加编辑。

标签: validation node.js express


【解决方案1】:

来自the README

Express Form 具有多种配置选项,但旨在为典型的 Express 应用程序提供合理的默认值。

...

dataSources (Array):在过滤和验证数据时用作数据源的 Express 请求属性数组。默认值:["body", "query", "params"]

所以按照这些思路应该可以解决问题:

var form = require('express-form')
           .configure({dataSources: ['body', 'files', 'query', 'params']});

【讨论】:

  • 谢谢!不知道我是怎么错过的。要补充的一件事。我将对我的原始问题添加一个编辑,显示我必须做些什么才能让它工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-11
  • 2011-03-10
  • 1970-01-01
  • 2015-01-03
  • 2016-09-23
  • 1970-01-01
  • 2023-03-15
相关资源
最近更新 更多