【发布时间】: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