Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
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
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 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
For integrating with Twitter bootstrap 3 (horizontal form), this is what you need to do:
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) {
object.widget.classes = object.widget.classes || [];
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:
form.toHTML(bootstrapField);
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.
A more detailed look at the methods and attributes available. Most of these you will not need to use directly.
Converts a form definition (an object literal containing field objects) into a form object.
Forms can be created with an optional "options" object as well.
validatePastFirstError
: true
, otherwise assumes false
false
, the first validation error will halt form validation.true
, all fields will be validated.fields
- Object literal containing the field objects passed to the create
functionInspects a request or object literal and binds any data to the correct fields.
Binds data to correct fields, returning a new bound form object.
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.
Contains the same methods as the unbound form, plus:
data
- Object containing all the parsed data keyed by field namefields
- Object literal containing the field objects passed to the create
functionCalls validate on each field in the bound form and returns the resulting form object to the callback.
Checks all fields for an error attribute. Returns false if any exist, otherwise returns true.
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.
label
- Optional label text which overrides the defaultrequired
- Boolean describing whether the field is mandatoryvalidators
- An array of functions which validate the field datawidget
- A widget object to use when rendering the fieldid
- An optional id to override the defaultchoices
- A list of options, used for multiple choice fieldscssClasses
- A list of CSS classes for label and field wrapperhideError
- if true, errors won't be rendered automaticallyerrorAfterField
- if true, the error message will be displayed after the field, rather than beforefieldsetClasses
- for widgets with a fieldset (multipleRadio and multipleCheckbox), set classes for the fieldsetlegendClasses
- for widgets with a fieldset (multipleRadio and multipleCheckbox), set classes for the fieldset's legendCoerces 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.
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.
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.
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.
Returns a string containing a label element with the correct 'for' attribute containing the text from field.labelText(name).
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.
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.
same as field object, but with a few extensions
value
- The raw value from the request datadata
- The request data coerced to the correct format for this fielderror
- An error message if the field fails validationChecks 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.
classes
- Custom classes to add to the rendered widgetlabelClasses
- 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'Returns a string containing a HTML representation of the widget for the given field.
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.
A function which accepts a name and field as arguments and returns a string containing a HTML representation of the field.
FAQs
An easy way to create, parse, and validate forms
The npm package forms receives a total of 1,330 weekly downloads. As such, forms popularity was classified as popular.
We found that forms demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.