项目作者: dandean

项目描述 :
Express的表单验证和数据过滤
高级语言: JavaScript
项目地址: git://github.com/dandean/express-form.git
创建时间: 2011-01-09T08:47:47Z
项目社区:https://github.com/dandean/express-form

开源协议:MIT License

下载


Primary fork has moved to freewil/express-form

Express Form provides data filtering and validation as route middleware to your Express applications.

Usage:

  1. var form = require("express-form"),
  2. field = form.field;
  3. var app = express.createServer();
  4. app.configure(function() {
  5. app.use(express.bodyDecoder());
  6. app.use(app.router);
  7. });
  8. app.post(
  9. // Route
  10. '/user',
  11. // Form filter and validation middleware
  12. form(
  13. field("username").trim().required().is(/^[a-z]+$/),
  14. field("password").trim().required().is(/^[0-9]+$/),
  15. field("email").trim().isEmail()
  16. ),
  17. // Express request-handler now receives filtered and validated data
  18. function(req, res){
  19. if (!req.form.isValid) {
  20. // Handle errors
  21. console.log(req.form.errors);
  22. } else {
  23. // Or, use filtered form data from the form object:
  24. console.log("Username:", req.form.username);
  25. console.log("Password:", req.form.password);
  26. console.log("Email:", req.form.email);
  27. }
  28. }
  29. );

Documentation:

Module

The Express Form module returns an Express Route Middleware function. You specify filtering and validation by passing filters and validators as arguments to the main module function. For example:

  1. var form = require("express-form");
  2. app.post('/user',
  3. // Express Form Route Middleware: trims whitespace off of
  4. // the `username` field.
  5. form(form.field("username").trim()),
  6. // standard Express handler
  7. function(req, res) {
  8. // ...
  9. }
  10. );

Fields

The field property of the module creates a filter/validator object tied to a specific field.

  1. field(fieldname[, label]);

You can access nested properties with either dot or square-bracket notation.

  1. field("post.content").minLength(50),
  2. field("post[user][id]").isInt(),
  3. field("post.super.nested.property").required()

Simply specifying a property like this, makes sure it exists. So, even if req.body.post was undefined, req.form.post.content would be defined. This helps avoid any unwanted errors in your code.

The API is chainable, so you can keep calling filter/validator methods one after the other:

  1. filter("username").trim().toLower().truncate(5).required().isAlphanumeric()

Filter API:

Type Coercion

  1. toFloat() -> Number
  2. toInt() -> Number, rounded down
  3. toBoolean() -> Boolean from truthy and falsy values
  4. toBooleanStrict() -> Only true, "true", 1 and "1" are `true`
  5. ifNull(replacement) -> "", undefined and null get replaced by `replacement`

HTML Encoding for & " < >

  1. entityEncode() -> encodes HTML entities
  2. entityDecode() -> decodes HTML entities

String Transformations

  1. trim(chars) -> `chars` defaults to whitespace
  2. ltrim(chars)
  3. rtrim(chars)
  4. toLower() / toLowerCase()
  5. toUpper() / toUpperCase()
  6. truncate(length) -> Chops value at (length - 3), appends `...`

Validator API:

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.

Use “%s” in the message to have the field name or label printed in the message:

  1. validate("username").required()
  2. // -> "username is required"
  3. validate("username").required("What is your %s?")
  4. // -> "What is your username?"
  5. validate("username", "Username").required("What is your %s?")
  6. // -> "What is your Username?"

Validation Methods

By Regular Expressions

  1. regex(pattern[, modifiers[, message]])
  2. - pattern (RegExp|String): RegExp (with flags) or String pattern.
  3. - modifiers (String): Optional, and only if `pattern` is a String.
  4. - message (String): Optional validation message.
  5. alias: is
  6. Checks that the value matches the given regular expression.
  7. Example:
  8. validate("username").is("[a-z]", "i", "Only letters are valid in %s")
  9. validate("username").is(/[a-z]/i, "Only letters are valid in %s")
  10. notRegex(pattern[, modifiers[, message]])
  11. - pattern (RegExp|String): RegExp (with flags) or String pattern.
  12. - modifiers (String): Optional, and only if `pattern` is a String.
  13. - message (String): Optional validation message.
  14. alias: not
  15. Checks that the value does NOT match the given regular expression.
  16. Example:
  17. validate("username").not("[a-z]", "i", "Letters are not valid in %s")
  18. validate("username").not(/[a-z]/i, "Letters are not valid in %s")

By Type

  1. isNumeric([message])
  2. isInt([message])
  3. isDecimal([message])
  4. isFloat([message])

By Format

  1. isEmail([message])
  2. isUrl([message])
  3. isIP([message])
  4. isAlpha([message])
  5. isAlphanumeric([message])
  6. isLowercase([message])
  7. isUppercase([message])

By Content

  1. notEmpty([message])
  2. Checks if the value is not just whitespace.
  3. equals( value [, message] )
  4. - value (String): A value that should match the field value OR a fieldname
  5. token to match another field, ie, `field::password`.
  6. Compares the field to `value`.
  7. Example:
  8. validate("username").equals("admin")
  9. validate("password").is(/^\w{6,20}$/)
  10. validate("password_confirmation").equals("field::password")
  11. contains(value[, message])
  12. - value (String): The value to test for.
  13. Checks if the field contains `value`.
  14. notContains(string[, message])
  15. - value (String): A value that should not exist in the field.
  16. Checks if the field does NOT contain `value`.

Other

  1. required([message])
  2. Checks that the field is present in form data, and has a value.

Array Method

  1. array()
  2. Using the array() flag means that field always gives an array. If the field value is an array, but there is no flag, then the first value in that array is used instead.
  3. This means that you don't have to worry about unexpected post data that might break your code. Eg/ when you call an array method on what is actually a string.
  4. field("project.users").array(),
  5. // undefined => [], "" => [], "q" => ["q"], ["a", "b"] => ["a", "b"]
  6. field("project.block"),
  7. // project.block: ["a", "b"] => "a". No "array()", so only first value used.
  8. In addition, any other methods called with the array method, are applied to every value within the array.
  9. field("post.users").array().toUpper()
  10. // post.users: ["one", "two", "three"] => ["ONE", "TWO", "THREE"]

Custom Methods

  1. custom(function[, message])
  2. - function (Function): A custom filter or validation function.
  3. This method can be utilised as either a filter or validator method.
  4. If the function throws an error, then an error is added to the form. (If `message` is not provided, the thrown error message is used.)
  5. If the function returns a value, then it is considered a filter method, with the field then becoming the returned value.
  6. If the function returns undefined, then the method has no effect on the field.
  7. Examples:
  8. If the `name` field has a value of "hello there", this would
  9. transform it to "hello-there".
  10. field("name").custom(function(value) {
  11. return value.replace(/\s+/g, "-");
  12. });
  13. Throws an error if `username` field does not have value "admin".
  14. field("username").custom(function(value) {
  15. if (value !== "admin") {
  16. throw new Error("%s must be 'admin'.");
  17. }
  18. });

http.ServerRequest.prototype.form

Express Form adds a form object with various properties to the request.

  1. isValid -> Boolean
  2. errors -> Array
  3. flashErrors(name) -> undefined
  4. Flashes all errors. Configurable, enabled by default.
  5. getErrors(name) -> Array or Object if no name given
  6. - fieldname (String): The name of the field
  7. Gets all errors for the field with the given name.
  8. You can also call this method with no parameters to get a map of errors for all of the fields.
  9. Example request handler:
  10. function(req, res) {
  11. if (!req.form.isValid) {
  12. console.log(req.errors);
  13. console.log(req.getErrors("username"));
  14. console.log(req.getErrors());
  15. }
  16. }

Configuration

Express Form has various configuration options, but aims for sensible defaults for a typical Express application.

  1. form.configure(options) -> self
  2. - options (Object): An object with configuration options.
  3. flashErrors (Boolean): If validation errors should be automatically passed to Express flash() method. Default: true.
  4. autoLocals (Boolean): If field values from Express request.body should be passed into Express response.locals object. This is helpful when a form is invalid an you want to repopulate the form elements with their submitted values. Default: true.
  5. Note: if a field name dash-separated, the name used for the locals object will be in camelCase.
  6. dataSources (Array): An array of Express request properties to use as data sources when filtering and validating data. Default: ["body", "query", "params"].
  7. autoTrim (Boolean): If true, all fields will be automatically trimmed. Default: false.
  8. passThrough (Boolean): If true, all data sources will be merged with `req.form`. Default: false.

Installation:

  1. npm install express-form

Credits

Currently, Express Form uses many of the validation and filtering functions provided by Chris O’Hara’s node-validator.