Form validation and data filtering for Express
Last updated 4 years ago by freewil .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install express-form 
SYNC missed versions from official npm registry.

express-form Build Status

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


npm install express-form --save


var express = require('express'),
    bodyParser = require('body-parser'),
    form = require('express-form'),
    field = form.field;

var app = express();

  // Route

  // Form filter and validation middleware

   // Express request-handler now receives filtered and validated data
   function(req, res){
     if (!req.form.isValid) {
       // Handle errors

     } else {
       // Or, use filtered form data from the form object:
       console.log("Username:", req.form.username);
       console.log("Password:", req.form.password);




express-form 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:

var form = require("express-form");'/user',

  // Express Form Route Middleware: trims whitespace off of
  // the `username` field.

  // standard Express handler
  function(req, res) {
    // ...


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

field(fieldname[, label]);

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


Simply specifying a property like this, makes sure it exists. So, even if was undefined, 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:


Filter API:

Type Coercion

toFloat()           -> Number

toInt()             -> Number, rounded down

toBoolean()         -> Boolean from truthy and falsy values

toBooleanStrict()   -> Only true, "true", 1 and "1" are `true`

ifNull(replacement) -> "", undefined and null get replaced by `replacement`

HTML Encoding for & " < >

entityEncode() -> encodes HTML entities

entityDecode() -> decodes HTML entities

String Transformations

trim(chars)                 -> `chars` defaults to whitespace



toLower() / toLowerCase()

toUpper() / toUpperCase()

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. required() allows you to set a placeholder (or default value) that your form contains when originally presented to the user. This prevents the placeholder value from passing the required() check.

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

// -> "username is required"

validate("username").required("Type your desired username", "What is your %s?")
// -> "What is your username?"

validate("username", "Username").required("", "What is your %s?")
// -> "What is your Username?"

Validation Methods

By Regular Expressions

regex(pattern[, modifiers[, message]])
- pattern (RegExp|String): RegExp (with flags) or String pattern.
- modifiers (String): Optional, and only if `pattern` is a String.
- message (String): Optional validation message.

    alias: is

    Checks that the value matches the given regular expression.


    validate("username").is("[a-z]", "i", "Only letters are valid in %s")
    validate("username").is(/[a-z]/i, "Only letters are valid in %s")

notRegex(pattern[, modifiers[, message]])
- pattern (RegExp|String): RegExp (with flags) or String pattern.
- modifiers (String): Optional, and only if `pattern` is a String.
- message (String): Optional validation message.

    alias: not

    Checks that the value does NOT match the given regular expression.


    validate("username").not("[a-z]", "i", "Letters are not valid in %s")
    validate("username").not(/[a-z]/i, "Letters are not valid in %s")

By Type





By Format









By Content


    Checks if the value is not just whitespace.

equals( value [, message] )
- value (String): A value that should match the field value OR a fieldname
                  token to match another field, ie, `field::password`.

    Compares the field to `value`.



contains(value[, message])
- value (String): The value to test for.

    Checks if the field contains `value`.

notContains(string[, message])
- value (String): A value that should not exist in the field.

    Checks if the field does NOT contain `value`.

minLength(length[, message])
- length (integer): The min character to test for.

    Checks the field value min length.

maxLength(length[, message])
- length (integer): The max character to test for.

    Checks the field value max length.



    Checks that the field is present in form data, and has a value.

Array Method

    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.

    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.

    // undefined => [], "" => [], "q" => ["q"], ["a", "b"] => ["a", "b"]

    // project.block: ["a", "b"] => "a". No "array()", so only first value used.

    In addition, any other methods called with the array method, are applied to every value within the array.

    // post.users: ["one", "two", "three"] => ["ONE", "TWO", "THREE"]

Custom Methods

custom(function[, message])
- function (Function): A custom filter or validation function.

    This method can be utilised as either a filter or validator method.

    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.)

    If the function returns a value, then it is considered a filter method, with the field then becoming the returned value.

    If the function returns undefined, then the method has no effect on the field.


    If the `name` field has a value of "hello there", this would
    transform it to "hello-there".

    field("name").custom(function(value) {
      return value.replace(/\s+/g, "-");

    Throws an error if `username` field does not have value "admin".

    field("username").custom(function(value) {
        if (value !== "admin") {
            throw new Error("%s must be 'admin'.");

    Validator based value on another field of the incoming source being validated

    field("sport", "favorite sport").custom(function(value, source) {
      if (! {
        throw new Error('unable to validate %s');

      switch ( {
        case 'US':
          if (value !=== 'baseball') {
            throw new Error('America likes baseball');

        case 'UK':
          if (value !=== 'football') {
            throw new Error('UK likes football');


    Asynchronous custom validator (3 argument function signature)

    form.field('username').custom(function(value, source, callback) {
      username.check(value, function(err) {
        if (err) return callback(new Error('Invalid %s'));


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

isValid -> Boolean

errors  -> Array

flashErrors(name) -> undefined

    Flashes all errors. Configurable, enabled by default.

getErrors(name) -> Array or Object if no name given
- fieldname (String): The name of the field

    Gets all errors for the field with the given name.

    You can also call this method with no parameters to get a map of errors for all of the fields.

Example request handler:

function(req, res) {
  if (!req.form.isValid) {


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

form.configure(options) -> self
- options (Object): An object with configuration options.

flashErrors (Boolean): If validation errors should be automatically passed to Express’ flash() method. Default: true.

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.

Note: if a field name dash-separated, the name used for the locals object will be in camelCase.

dataSources (Array): An array of Express request properties to use as data sources when filtering and validating data. Default: ["body", "query", "params"].

autoTrim (Boolean): If true, all fields will be automatically trimmed. Default: false.

passThrough (Boolean): If true, all data sources will be merged with `req.form`. Default: false.


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

Current Tags

  • 0.12.6                                ...           latest (4 years ago)

34 Versions

  • 0.12.6                                ...           4 years ago
  • 0.12.5                                ...           4 years ago
  • 0.12.4                                ...           5 years ago
  • 0.12.3                                ...           6 years ago
  • 0.11.2                                ...           6 years ago
  • 0.12.2                                ...           6 years ago
  • 0.12.1                                ...           6 years ago
  • 0.11.1                                ...           6 years ago
  • 0.12.0                                ...           6 years ago
  • 0.11.0                                ...           6 years ago
  • 0.10.1                                ...           7 years ago
  • 0.9.1                                ...           7 years ago
  • 0.9.0                                ...           7 years ago
  • 0.10.0                                ...           7 years ago
  • 0.7.2                                ...           7 years ago
  • 0.8.1                                ...           7 years ago
  • 0.8.0                                ...           7 years ago
  • 0.7.1                                ...           7 years ago
  • 0.7.0                                ...           7 years ago
  • 0.6.3                                ...           7 years ago
  • 0.6.2                                ...           9 years ago
  • 0.6.1                                ...           9 years ago
  • 0.6.0                                ...           9 years ago
  • 0.5.3                                ...           9 years ago
  • 0.5.2                                ...           9 years ago
  • 0.5.1                                ...           9 years ago
  • 0.5.0                                ...           9 years ago
  • 0.4.2                                ...           9 years ago
  • 0.4.1                                ...           9 years ago
  • 0.4.0                                ...           9 years ago
  • 0.3.0                                ...           9 years ago
  • 0.2.0                                ...           9 years ago
  • 0.1.1                                ...           9 years ago
  • 0.1.0                                ...           9 years ago
Maintainers (2)
Today 0
This Week 1
This Month 7
Last Day 1
Last Week 1
Last Month 12
Dependencies (3)
Dev Dependencies (4)

Copyright 2014 - 2016 © |