1 | Express Form provides data filtering and validation as route middleware to your Express applications.
|
2 |
|
3 | Usage:
|
4 | ------
|
5 |
|
6 | var form = require("express-form"),
|
7 | filter = form.filter,
|
8 | validate = form.validate;
|
9 |
|
10 | var app = express.createServer();
|
11 |
|
12 | app.configure(function() {
|
13 | app.use(express.bodyDecoder());
|
14 | app.use(app.router);
|
15 | });
|
16 |
|
17 | app.post(
|
18 |
|
19 | // Route
|
20 | '/user',
|
21 |
|
22 | // Form filter and validation middleware
|
23 | form(
|
24 | filter("username").trim(),
|
25 | validate("username").required().is(/^[a-z]+$/),
|
26 | filter("password").trim(),
|
27 | validate("password").required().is(/^[0-9]+$/),
|
28 | filter("email").trim(),
|
29 | validate("email").isEmail()
|
30 | ),
|
31 |
|
32 | // Express request-handler now receives filtered and validated data
|
33 | function(req, res){
|
34 | if (!req.form.isValid) {
|
35 | // Handle errors
|
36 | console.log(req.form.errors);
|
37 |
|
38 | } else {
|
39 | // Or, use filtered form data from the form object:
|
40 | console.log("Username:", req.form.username);
|
41 | console.log("Password:", req.form.password);
|
42 | console.log("Email:", req.form.email);
|
43 | }
|
44 | }
|
45 | );
|
46 |
|
47 | Documentation:
|
48 | --------------
|
49 |
|
50 | ### Module
|
51 |
|
52 | The Express Form **module** returns an Express [Route Middleware](http://expressjs.com/guide.html#Route-Middleware) function. You specify filtering and validation by passing filters and validators as arguments to the main module function. For example:
|
53 |
|
54 | var form = require("express-form");
|
55 |
|
56 | app.post('/user',
|
57 |
|
58 | // Express Form Route Middleware: trims whitespace off of
|
59 | // the `username` field.
|
60 | form(form.filter("username").trim()),
|
61 |
|
62 | // standard Express handler
|
63 | function(req, res) {
|
64 | // ...
|
65 | }
|
66 | );
|
67 |
|
68 |
|
69 | ### Filters
|
70 |
|
71 | The `filter` property of the module creates a filter object tied to a specific field.
|
72 |
|
73 | filter(fieldname);
|
74 | // -> Filter
|
75 |
|
76 | The API is chainable, so you can keep calling filter methods one after the other:
|
77 |
|
78 | filter("username").trim().toLower().truncate(5)
|
79 |
|
80 |
|
81 | #### Filter API:
|
82 |
|
83 | Type Coercion
|
84 |
|
85 | toFloat() -> Number
|
86 |
|
87 | toInt() -> Number, rounded down
|
88 |
|
89 | toBoolean() -> Boolean from truthy and falsy values
|
90 |
|
91 | toBooleanStrict() -> Only true, "true", 1 and "1" are `true`
|
92 |
|
93 | ifNull(replacement) -> "", undefined and null get replaced by `replacement`
|
94 |
|
95 |
|
96 | HTML Encoding for `& " < >`
|
97 |
|
98 | entityEncode() -> encodes HTML entities
|
99 |
|
100 | entityDecode() -> decodes HTML entities
|
101 |
|
102 |
|
103 | String Transformations
|
104 |
|
105 | trim(chars) -> `chars` defaults to whitespace
|
106 |
|
107 | ltrim(chars)
|
108 |
|
109 | rtrim(chars)
|
110 |
|
111 | toLower() / toLowerCase()
|
112 |
|
113 | toUpper() / toUpperCase()
|
114 |
|
115 | truncate(length) -> Chops value at (length - 3), appends `...`
|
116 |
|
117 |
|
118 | Custom Filters
|
119 |
|
120 | custom(function)
|
121 |
|
122 | Filters the field value using custom logic.
|
123 |
|
124 | Example:
|
125 | If the `name` field has a value of "hello there", this would
|
126 | transform it to "hello-there".
|
127 |
|
128 | filter("name").custom(function(value) {
|
129 | return value.replace(/\s+/g, "-");
|
130 | });
|
131 |
|
132 |
|
133 | ### Validators
|
134 |
|
135 | The `validate` property of the module creates a validator object tied to a specific field.
|
136 |
|
137 | validate(fieldname[, label]);
|
138 | // -> Validator
|
139 |
|
140 | The API is chainable, so you can keep calling validator methods one after the other:
|
141 |
|
142 | validate("username").required().isAlphanumeric()
|
143 |
|
144 |
|
145 | #### Validator API:
|
146 |
|
147 | **Validation messages**: each validator has its own default validation message. These can easily be overridden at runtime by passing a custom validation message to the validator. The custom message is always the **last** argument passed to the validator.
|
148 |
|
149 | Use "%s" in the message to have the field name or label printed in the message:
|
150 |
|
151 | validate("username").required()
|
152 | // -> "username is required"
|
153 |
|
154 | validate("username").required("What is your %s?")
|
155 | // -> "What is your username?"
|
156 |
|
157 | validate("username", "Username").required("What is your %s?")
|
158 | // -> "What is your Username?"
|
159 |
|
160 |
|
161 | **Validation Methods**
|
162 |
|
163 | *By Regular Expressions*
|
164 |
|
165 | regex(pattern[, modifiers[, message]])
|
166 | - pattern (RegExp|String): RegExp (with flags) or String pattern.
|
167 | - modifiers (String): Optional, and only if `pattern` is a String.
|
168 | - message (String): Optional validation message.
|
169 |
|
170 | alias: is
|
171 |
|
172 | Checks that the value matches the given regular expression.
|
173 |
|
174 | Example:
|
175 |
|
176 | validate("username").is("[a-z]", "i", "Only letters are valid in %s")
|
177 | validate("username").is(/[a-z]/i, "Only letters are valid in %s")
|
178 |
|
179 |
|
180 | notRegex(pattern[, modifiers[, message]])
|
181 | - pattern (RegExp|String): RegExp (with flags) or String pattern.
|
182 | - modifiers (String): Optional, and only if `pattern` is a String.
|
183 | - message (String): Optional validation message.
|
184 |
|
185 | alias: not
|
186 |
|
187 | Checks that the value does NOT match the given regular expression.
|
188 |
|
189 | Example:
|
190 |
|
191 | validate("username").not("[a-z]", "i", "Letters are not valid in %s")
|
192 | validate("username").not(/[a-z]/i, "Letters are not valid in %s")
|
193 |
|
194 |
|
195 | *By Type*
|
196 |
|
197 | isNumeric([message])
|
198 |
|
199 | isInt([message])
|
200 |
|
201 | isDecimal([message])
|
202 |
|
203 | isFloat([message])
|
204 |
|
205 |
|
206 | *By Format*
|
207 |
|
208 | isEmail([message])
|
209 |
|
210 | isUrl([message])
|
211 |
|
212 | isIP([message])
|
213 |
|
214 | isAlpha([message])
|
215 |
|
216 | isAlphanumeric([message])
|
217 |
|
218 | isLowercase([message])
|
219 |
|
220 | isUppercase([message])
|
221 |
|
222 |
|
223 | *By Content*
|
224 |
|
225 | notEmpty([message])
|
226 |
|
227 | Checks if the value is not just whitespace.
|
228 |
|
229 |
|
230 | equals( value [, message] )
|
231 | - value (String): A value that should match the field value OR a fieldname
|
232 | token to match another field, ie, `field::password`.
|
233 |
|
234 | Compares the field to `value`.
|
235 |
|
236 | Example:
|
237 | validate("username").equals("admin")
|
238 |
|
239 | validate("password").is(/^\w{6,20}$/)
|
240 | validate("password_confirmation").equals("field::password")
|
241 |
|
242 |
|
243 | contains(value[, message])
|
244 | - value (String): The value to test for.
|
245 |
|
246 | Checks if the field contains `value`.
|
247 |
|
248 |
|
249 | notContains(string[, message])
|
250 | - value (String): A value that should not exist in the field.
|
251 |
|
252 | Checks if the field does NOT contain `value`.
|
253 |
|
254 |
|
255 | *Other*
|
256 |
|
257 | required([message])
|
258 |
|
259 | Checks that the field is present in form data, and has a value.
|
260 |
|
261 |
|
262 | custom(function[, message])
|
263 | - function (Function): A custom validation function.
|
264 |
|
265 | Validates the field using a custom validation function. If the function
|
266 | throws, and `message` is not provided, the thrown error message is used.
|
267 |
|
268 | Example:
|
269 |
|
270 | validate("username").custom(function(value) {
|
271 | if (value !== "admin") {
|
272 | throw new Error("%s must be 'admin'.");
|
273 | }
|
274 | });
|
275 |
|
276 |
|
277 |
|
278 | ### http.ServerRequest.prototype.form
|
279 |
|
280 | Express Form adds a `form` object with various properties to the request.
|
281 |
|
282 | isValid -> Boolean
|
283 |
|
284 | errors -> Array
|
285 |
|
286 | flashErrors(name) -> undefined
|
287 |
|
288 | Flashes all errors. Configurable, enabled by default.
|
289 |
|
290 | getErrors(name) -> Array
|
291 | - fieldname (String): The name of the field
|
292 |
|
293 | Gets all errors for the field with the given name.
|
294 |
|
295 | Example request handler:
|
296 |
|
297 | function(req, res) {
|
298 | if (req.isValid == false) {
|
299 | console.log(req.errors);
|
300 | console.log(req.getErrors("username"))
|
301 | }
|
302 | }
|
303 |
|
304 |
|
305 | Installation:
|
306 | -------------
|
307 |
|
308 | npm install express-form
|
309 |
|
310 |
|
311 | Credits
|
312 | -------
|
313 |
|
314 | Currently, Express Form uses many of the validation and filtering functions provided by Chris O'Hara's [node-validator](https://github.com/chriso/node-validator).
|