Reputation: 17583
I'm using express-form
https://github.com/dandean/express-form
Does it have the ability to validate an input of the type file
? I specifically want to require
that someone upload a file.
EDIT for Linus :)
I've tried:
field("pdf").required("pdf", "You must select a file to upload.")
The problem is that this is looking for req.body.pdf
not req.files.pdf
, so it always thinks the validation fails.
EDIT / WORKING CODE: What I did to get it to work based on Linus' answer.
Not only did I need to configure the dataSources
param, I also needed to check the field's size
property as just doing a required
on the field isn't good enough because even if a file input is empty, it still exists (meta data, etc). So instead, I do a custom validation function that makes sure pdf.size
is greater than 0. In my code, I also check to see if I have a title
. I left that here in case anyone was wondering how to string together multiple validations.
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."))
Upvotes: 1
Views: 1037
Reputation: 39261
From the README:
Express Form has various configuration options, but aims for sensible defaults for a typical Express application.
...
dataSources (Array): An array of Express request properties to use as data sources when filtering and validating data. Default:
["body", "query", "params"]
.
So something along these lines should do the trick:
var form = require('express-form')
.configure({dataSources: ['body', 'files', 'query', 'params']});
Upvotes: 1