formal

Simple, flexible node.js form module with casting and validation; inspired by mongoose

Formal

Formal is an awesome Form module for node.js with casting and validation inspired by mongoose!

var Form = require('formal');
 
var form = new Form({
  name: {
    family: String,
    first: {
      type: [String],
      setfunction(val) {return val.split(' ');}
    }
  },
  email: {
    type: String,
    required: true,
    match: /^[a-z0-9._-]+@[a-z0-9.-]{2,}[.][a-z]{2,3}$/,
    attributes: {
      type: 'email'
    }
  },
  age: {type: Number, min: 18}
});
 
form.set({
  name: {family: 'Martinez'},
  'name.first': 'José Luis Chavez',
  age: 12
});
 
form.validate(function (err) {
  console.log(err); // missing required email, age to low 
  console.log(form.get('name.first.0')); // José 
  console.log(form.export());
});

npm install formal --save

This module focus on form field casting and validation, with suppports for advanced path definition.

  • field of type: String, Number, Date, Boolean and [of each type] (Arrays)
  • dot.F.notation path à la mongoose to access field and for.arrays.0 too
  • shortcut validators, for required, enum, min, max and match to match mongoose
  • shortcut setters mimicking mongoose for trim, lowercase and uppercase
  • setters & getters
  • custom validators
  • virtuals
  • route-middleware to work seamlessy with express or connect
  • ... and of course it match mongoose but works fine without mongoose
  • render form to html (this will be supported via an external module)
  • support for sub-Form
  • support for sub-[Form]
  • incoming npm module to define the form from an existing mongoose schema
  • incoming npm (decorator) module to render the form into html via consolidate.js
  • support browser

Summary of the most useful methods.
For a complete list see gh-pages documentation.

For connect and express the alternative factory method can be used as a quick helper to create a new instance and return form.middleware() to monkey patch the request and response object.

app.post('/url',
  // sames as (new Form({...})).middleware() 
  form({
    fieldA: String
  }),
  function (reqres) {
    console.log(req.body.form);
    console.log(res.locals.form.fieldA.value);
  }
);

Define a new field.

form.set({
  example: {
    'of.a.nested.field': String
  }
});

Validate all fields and return an err object, if any, via the callback function.

Provide a route-middleware à la connect/express which will monkey patch the req.body.form and res.locals.form.

npm test
Mocha Coverage
npm run-script coverage
On Coveralls.io

All tests are in Coffee-script, hence easy to read! Provides a great way to understand the API ;)

MIT