包详细信息

forms

caolan9.2kMIT1.3.2

An easy way to create, parse, and validate forms

自述文件

Forms Version Badge

Build Status dependency status dev dependency status License Downloads

npm badge

Constructing a good form by hand is a lot of work. Popular frameworks like Ruby on Rails and Django contain code to make this process less painful. This module is an attempt to provide the same sort of helpers for node.js.

$ npm install forms

Contribute

This code is still in its infancy, and I'd really appreciate any contributions, bug reports, or advice. Especially on the following key areas:

  • Creating sensible default rendering functions that generate flexible, accessible markup. This is an early priority because without being confident that the standard markup won't change under their feet, developers will not be able to adopt the module for any sort of production use.
  • Exploring write-once validation that works on the client and the server. There are some unique advantages to using the same language at both ends, let's try and make the most of it!
  • Ensuring it's easy to use with existing node web frameworks. Ideally this module would integrate well with projects using any of the popular frameworks.

    Contributors

  • ljharb

  • ivanquirino
  • richardngn
  • caulagi
  • …and many more

Example

Creating an example registration form:

var forms = require('forms');
var fields = forms.fields;
var validators = forms.validators;

var reg_form = forms.create({
    username: fields.string({ required: true }),
    password: fields.password({ required: validators.required('You definitely want a password') }),
    confirm:  fields.password({
        required: validators.required('don\'t you know your own password?'),
        validators: [validators.matchField('password')]
    }),
    email: fields.email()
});

Rendering a HTML representation of the form:

reg_form.toHTML();

Would produce:

<div class="field required">
    <label for="id_username">Username</label>
    <input type="text" name="username" id="id_username" value="test" />
</div>
<div class="field required">
    <label for="id_password">Password</label>
    <input type="password" name="password" id="id_password" value="test" />
</div>
<div class="field required">
    <label for="id_confirm">Confirm</label>
    <input type="password" name="confirm" id="id_confirm" value="test" />
</div>
<div class="field">
    <label for="id_email">Email</label>
    <input type="text" name="email" id="id_email" />
</div>

You'll notice you have to provide your own form tags and submit button, its more flexible this way ;)

Handling a request:

function myView(req, res) {
    reg_form.handle(req, {
        success: function (form) {
            // there is a request and the form is valid
            // form.data contains the submitted data
        },
        error: function (form) {
            // the data in the request didn't validate,
            // calling form.toHTML() again will render the error messages
        },
        empty: function (form) {
            // there was no form data in the request
        }
    });
}

That's it! For more detailed / working examples look in the example folder. An example server using the form above can be run by doing:

$ node example/simple.js

Bootstrap compatible output

For integrating with Twitter bootstrap 3 (horizontal form), this is what you need to do:

var widgets = require('forms').widgets;

var my_form = forms.create({
    title: fields.string({
        required: true,
        widget: widgets.text({ classes: ['input-with-feedback'] }),
        errorAfterField: true,
        cssClasses: {
            label: ['control-label col col-lg-3']
        }
    }),
    description: fields.string({
        errorAfterField: true,
        widget: widgets.text({ classes: ['input-with-feedback'] }),
        cssClasses: {
            label: ['control-label col col-lg-3']
        }
    })
});

var bootstrapField = function (name, object) {
    if (!Array.isArray(object.widget.classes)) { object.widget.classes = []; }
    if (object.widget.classes.indexOf('form-control') === -1) {
        object.widget.classes.push('form-control');
    }

    var label = object.labelHTML(name);
    var error = object.error ? '<div class="alert alert-error help-block">' + object.error + '</div>' : '';

    var validationclass = object.value && !object.error ? 'has-success' : '';
    validationclass = object.error ? 'has-error' : validationclass;

    var widget = object.widget.toHTML(name, object);
    return '<div class="form-group ' + validationclass + '">' + label + widget + error + '</div>';
};

And while rendering it:

reg_form.toHTML(bootstrapField);

Available types

A list of the fields, widgets, validators and renderers available as part of the forms module. Each of these components can be switched with customised components following the same API.

Fields

  • string
  • number
  • boolean
  • array
  • password
  • email
  • tel
  • url
  • date

Widgets

  • text
  • email
  • number
  • password
  • hidden
  • color
  • tel
  • date
  • checkbox
  • select
  • textarea
  • multipleCheckbox
  • multipleRadio
  • multipleSelect
  • label

Validators

  • matchField
  • matchValue
  • required
  • requiresFieldIfEmpty
  • min
  • max
  • range
  • minlength
  • maxlength
  • rangelength
  • regexp
  • color
  • email
  • url
  • date
  • alphanumeric
  • digits
  • integer

Renderers

  • div
  • p
  • li
  • table

API

A more detailed look at the methods and attributes available. Most of these you will not need to use directly.

forms.create(fields)

Converts a form definition (an object literal containing field objects) into a form object.

forms.create(fields, options)

Forms can be created with an optional "options" object as well.

Supported options:

  • validatePastFirstError: true, otherwise assumes false
    • If false, the first validation error will halt form validation.
    • If true, all fields will be validated.

Form object

Attributes

  • fields - Object literal containing the field objects passed to the create function

form.handle(req, callbacks)

Inspects a request or object literal and binds any data to the correct fields.

form.bind(data)

Binds data to correct fields, returning a new bound form object.

form.toHTML(iterator)

Runs toHTML on each field returning the result. If an iterator is specified, it is called for each field with the field name and object as its arguments, the iterator's results are concatenated to create the HTML output, allowing for highly customised markup.

Bound Form object

Contains the same methods as the unbound form, plus:

Attributes

  • data - Object containing all the parsed data keyed by field name
  • fields - Object literal containing the field objects passed to the create function

form.validate(callback)

Calls validate on each field in the bound form and returns the resulting form object to the callback.

form.isValid()

Checks all fields for an error attribute. Returns false if any exist, otherwise returns true.

form.toHTML(iterator)

Runs toHTML on each field returning the result. If an iterator is specified, it is called for each field with the field name and object as its arguments, the iterator's results are concatenated to create the HTML output, allowing for highly customised markup.

Field object

Attributes

  • label - Optional label text which overrides the default
  • required - Boolean describing whether the field is mandatory
  • validators - An array of functions which validate the field data
  • widget - A widget object to use when rendering the field
  • id - An optional id to override the default
  • choices - A list of options, used for multiple choice fields (see the field.choices section below)
  • cssClasses - A list of CSS classes for label and field wrapper
  • hideError - if true, errors won't be rendered automatically
  • labelAfterField - if true, the label text will be displayed after the field, rather than before
  • errorAfterField - if true, the error message will be displayed after the field, rather than before
  • fieldsetClasses - for widgets with a fieldset (multipleRadio and multipleCheckbox), set classes for the fieldset
  • legendClasses - for widgets with a fieldset (multipleRadio and multipleCheckbox), set classes for the fieldset's legend

field.choices

The choices property is used for radio, checkbox, and select fields. Two formats are supported and in case of select fields the format can be nested once to support option groups.

The first format is based on objects and is easy to write. Object keys are treated as values and object values are treated as labels. If the value is another object and nesting is supported by the widget the key will be used as label and the value as nested list.

The second format is array-based and therefore ordered (object keys are unordered by definition). The array should contain arrays with two values the first being the value and the second being the label. If the label is an array and nesting is supported by the widget the value will be used as label and the label as nested list.

Both formats are demonstrated below:

// objects
{
    'val-1': 'text-1',
    'val-2': 'text-2',
    'text-3': {
        'nested-val-1': 'nested-text-1',
        'nested-val-2': 'nested-text-2',
        'nested-val-3': 'nested-text-3'
    }
}

// arrays
[
    ['val-1', 'text-1'],
    ['val-2', 'text-2'],
    ['text-3', [
        ['nested-val-1', 'nested-text-1'],
        ['nested-val-2', 'nested-text-2'],
        ['nested-val-3', 'nested-text-3'],
    ]]
]

field.parse(rawdata)

Coerces the raw data from the request into the correct format for the field, returning the result, e.g. '123' becomes 123 for the number field.

field.bind(rawdata)

Returns a new bound field object. Calls parse on the data and stores in the bound field's data attribute, stores the raw value in the value attribute.

field.errorHTML()

Returns a string containing a HTML element containing the fields error message, or an empty string if there is no error associated with the field.

field.labelText(name)

Returns a string containing the label text from field.label, or defaults to using the field name with underscores replaced with spaces and the first letter capitalised.

field.labelHTML(name, id)

Returns a string containing a label element with the correct 'for' attribute containing the text from field.labelText(name).

field.classes()

Returns an array of default CSS classes considering the field's attributes, e.g. ['field', 'required', 'error'] for a required field with an error message.

field.toHTML(name, iterator)

Calls the iterator with the name and field object as arguments. Defaults to using forms.render.div as the iterator, which returns a HTML representation of the field label, error message and widget wrapped in a div.

Bound Field object

same as field object, but with a few extensions

Attributes

  • value - The raw value from the request data
  • data - The request data coerced to the correct format for this field
  • error - An error message if the field fails validation

validate(callback)

Checks if the field is required and whether it is empty. Then runs the validator functions in order until one fails or they all pass. If a validator fails, the resulting message is stored in the field's error attribute.

Widget object

Attributes

  • classes - Custom classes to add to the rendered widget
  • labelClasses - Custom classes to add to the choices label when applicable (multipleRadio and multipleCheckbox)
  • type - A string representing the widget type, e.g. 'text' or 'checkbox'

toHTML(name, field)

Returns a string containing a HTML representation of the widget for the given field.

Validator

A function that accepts a bound form, bound field and a callback as arguments. It should apply a test to the field to assert its validity. Once processing has completed it must call the callback with no arguments if the field is valid or with an error message if the field is invalid.

Renderer

A function which accepts a name and field as arguments and returns a string containing a HTML representation of the field.

更新日志

1.3.2 / 2020-06-08

  • [Fix] validators.email: allowing comments, prevent catastrophic backtracking (#214)
  • [Deps] update array.prototype.every, array.prototype.some, async, formidable, qs, string.prototype.trim
  • [Dev Deps] update eslint, @ljharb/eslint-config, evalmd, tape; add aud, safe-publish-latest
  • [Tests] add test with only boolean fields (#205)
  • [Tests] add more bizarre but valid email tests
  • [Tests] improve error messages
  • [Tests] validators.email: refactor tests, add some passing tests
  • [Tests] use shared travis-ci configs

1.3.1 / 2019-05-03

  • [Fix] length validators should work with both strings and numbers (#204)
  • [Fix] ES3: use array.prototype.{some,every} instead of Array#{some,every}
  • [Fix] ES3: use reduce instead of Array#reduce
  • [Deps] update async, formidable, is, object-keys, object.assign, qs, reduce
  • [Dev Deps] update tape, eslint, @ljharb/eslint-config, nsp, covert
  • [Dev Deps] remove testling, jscs
  • [Tests] use npx aud instead of nsp or npm audit with hoops
  • [Tests] up to node v12.1, v11.14, v10.15, v9.11, v8.15, v7.10, v6.17, v4.9; use nvm install-latest-npm; run coverage tests but allow failure, for now

1.3.0 / 2016-11-15

  • [New] implement nested and ordered choices (#191)
  • [New] [Fix] ensure that all content in tag is properly escaped
  • [Fix] use is.array instead of Array.isArray, to continue supporting ES3
  • [Fix] ES3: use object-keys instead of Object.keys
  • [Deps] update is, async, qs
  • [Dev Deps] update eslint, @ljharb/eslint-config, nsp, tape
  • [Tests] up to node v7.0, v6.9, v4.6; improve test matrix
  • [Tests] execute all tests in test directory (#190)

1.2.0 / 2016-08-25

  • [New] Add labelAfterField option when rendering (#183)
  • [Deps] update qs, async, object.assign, string.prototype.trim
  • [Dev Deps] update tape, jscs, eslint, @ljharb/eslint-config, nsp, evalmd
  • [Tests] up to node v6.4, v5.12, v4.5
  • [Tests] use tape-dom for browser tests
  • [Tests] fix npm upgrades for older nodes

1.1.4 / 2015-09-22

  • [Deps] update async, object.assign, string.prototype.trim, qs, is
  • [Dev Deps] update tape, jscs, evalmd, eslint, @ljharb/eslint-config, nsp
  • [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG.
  • [Tests] Add evalmd to verify that code example blocks in the README are correct.
  • [Tests] up to io.js v3.3, node v4.1

1.1.3 / 2015-08-08

  • [Fix] Ensure that nested required fields, even when the nesting namespace is omitted, are still validated (#165)
  • [Fix] Ensure validatePastFirstError setting propagates through to object fields
  • [Fix] Disable parseArrays in qs.parse
  • [Refactor] Use string.prototype.trim package instead of my copy-pasted code.
  • [Deps] Update async, qs, object.assign
  • [Dev Deps] Update eslint, tape; add my shared eslint config
  • [Tests] Test up to io.js v3.0
  • [Tests] Add npm run security
  • [Docs] Update bootstrap example to avoid duplicate form-control classes (#163)

1.1.2 / 2015-05-30

  • Code cleanup: Avoid ES3 syntax errors, just in case.
  • Code cleanup: Avoid reusing variables.
  • Code cleanup: Remove or use unused variables.
  • Code cleanup: Avoid reassigning function params, for performance
  • Test up to io.js v2.1, and latest node
  • Add npm run eslint
  • Update tape, jscs, is, formidable, qs, object.assign, covert, async

1.1.1 / 2015-01-06

  • Fix validation error bug with nested fields. (#153)
  • Update formidable, jscs

1.1.0 / 2014-12-16

  • Use label text instead of field name consistently in error messages
  • Fix support of zero values in inputs (#147)
  • Update qs, is, object.assign, tape, covert, jscs

1.0.0 / 2014-09-29

  • v1.0.0 - it’s time.
  • Update CHANGELOG

0.10.0 / 2014-09-24

  • Updating testling, qs, jscs, tape
  • Cleaning up URLs in README
  • Adding license and downloads badges.
  • Adding a single "license" field to package.json

0.9.6 / 2014-09-03

  • Updating is, jscs, qs, jscs

0.9.5 / 2014-08-29

  • Updating formidable, qs, jscs

0.9.4 / 2014-08-28

  • Updating qs

0.9.2 / 2014-08-25

  • Updating is, covert, tape
  • Clean up README (#139); use SVG badges instead of PNG

0.9.1 / 2014-08-07

  • Updating qs and tape

0.9.0 / 2014-07-30

  • Add option to disable automatic error rendering (#138)

0.8.2 / 2014-07-30

  • Add hideError option to disable automatic error rendering (#138)

0.8.1 / 2014-07-24

  • Fix/add support for empty <option> value attributes (#137)

0.8.0 / 2014-07-23 (mispublished and unpublished)

  • Fix inability to disable ID attribute (#128)
  • Add support for callback chaining (#129)

0.7.0 / 2014-05-20

  • Properly compare using string values in select, multipleSelect, multipleCheckbox, and multipleRadio
  • Add "placeholder" to textarea elements

0.6.0 / 2014-05-03

  • Add fieldsetClasses, legendClasses, and labelClasses

0.5.0 / 2014-05-01

  • Added new form-level validatePastFirstErrorOption. When true, all fields will validate, instead of stopping at the first error.
  • Internal refactoring for improved HTML tag generation

0.4.1 / 2014-04-24

  • Updating dependencies
  • Adding digits and integer validators

0.4.0 / 2014-04-07

  • Using https URLs in package.json
  • Updating async and tape.
  • Using is to check for things
  • Using better tape matchers, and is functions
  • Merge pull request #107 from timjrobinson/nested_fields_fix_fix Fixed bug where .bind with incomplete data was removing fields from form.
  • Fixed bug where if you bind data to a form fields that were missing from the data were being removed from the form.
  • Adding npm run coverage
  • Merge pull request #106 from timjrobinson/nested_fields_fix Fixed null object error when a nested form is submitted but one of the subsections is missing.
  • Fixed null pointer error when a nested form is submitted but one of the subsections is missing.
  • Adding another matchValue test.
  • Fixing whitespace; a bit of cleanup.
  • Add plan statements, and using the "t" convention inside tests.
  • Adding a matchValue validator. Relates to #82.
  • Removing the express example, primarily because it doesn’t work with express 3. Also, the dependency stuff is weird. This should go in a separate repo rather than living inside forms. Closes #93. Relates to #105.
  • Merge pull request #99 from Flaise/master Made %s string formatting tokens optional in field validator error messages.
  • Oops! Make sure we’re running all tests
  • Made %s string formatting tokens optional in field validator error messages.
  • Add number widget. From #83.
  • Pass an enctype in the simple example
  • Updating json-template. Note: it can’t be installed from npm because the package.json is invalid.
  • Merge pull request #101 from caolan/use_tape_for_tests Use tape for tests
  • Converting tests over to tape instead of nodeunit.
  • Using tape for tests instead.
  • Adding "alphanumeric" to README, per #98
  • Merge pull request #98 from Flaise/master Added alphanumeric validator for convenience.
  • Added alphanumeric validator for convenience.
  • Updating deps
  • Updating dev deps
  • Merge pull request #92 from shinnn/master Replace "!!!" with "doctype"
  • Replace "!!!" with "doctype"
  • Merge pull request #91 from kukulili-labs/master Add optional "tabindex"attribute to widgets
  • Fix test
  • Add optional "tabindex"attribute to widgets
  • Updating browserify
  • Remove node 0.6 workaround; test down to node 0.4
  • Adding is
  • Merge pull request #89 from timjrobinson/label-text Made label text for camel case or dash separated field names format nicely
  • Updating dependencies
  • Renaming variables.
  • Made label text for camel case or dash separated field names format nicely.
  • Make the complex example use POST and be multipart-encoded.
  • Use formidable to handle multipart-encoded form data.
  • HTML attributes should be double quoted.
  • Pass the method into the example template.
  • submit buttons are so much better than submit inputs.
  • Test in node 0.11 too
  • Unset strict SSL for node 0.6 in Travis-CI
  • Rearranging badges
  • Adding npm badge and version svg.
  • Updating browserify.
  • Merge branch "required_validator". Closes #81.
  • Use String() instead of the toString prototype method.
  • When the "required" option is true, use the default "required" validator. Otherwise, use the passed-in validator.
  • Adding a "required" validator.
  • Upgrading browserify.

0.3.0 / 2013-09-16

  • v0.3.0
  • Merge pull request #80 from path/dynamic-widget-attributes Add support for dynamic widget attributes
  • Add support for dynamic widget attributes Sometimes it is desirable to set widget attributes after the form is created. This makes it possible and should be fully backwards compatible.
  • Adding dev dependency badge.
  • Rearranging dependencies.
  • s/\t/ /g
  • Merge branch "nested_fields_merge" - merges #77, fixes #11
  • Using arguments.length to shift arguments.
  • Adding spacing.
  • Reverting this line.
  • Bumping dev deps.
  • Adding a trailing newline.
  • Adding a nested example.
  • Merge pull request #77

0.2.3 / 2013-08-25

  • v0.2.3
  • Adding testling browsers.
  • style corrections
  • Adding Travis CI info to the README. Closes #42.
  • Fixing indentation.
  • Fixing a syntax error.
  • Reusing some common placeholder functions in these tests.
  • Fixing a bug in my port of the String#trim shim, and cleaning it up a bit.
  • Moving a misplaced semicolon.
  • Moving this logic up into the closure.
  • Combining var declarations.
  • Removing arbitrary line breaks.
  • Making sure "use strict" is always inside a function.
  • Merge pull request #78 from caolan/either_or Adds "requiresFieldIfEmpty" validator
  • Adding requiresFieldIfEmpty validator.
  • If any field validator functions have a forceValidation property set, validate even when empty.
  • take object literals as nested fields
  • Adding ES5’s String#trim
  • Removing an extra space
  • compatibility