Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

express-form

Package Overview
Dependencies
Maintainers
0
Versions
34
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

express-form - npm Package Compare versions

Comparing version 0.1.1 to 0.2.0

test/._form.test.js

2

._index.js

@@ -1,4 +0,4 @@

Mac OS X  2��ATTR�{���!�!com.macromates.caret{
Mac OS X  2��ATTR�#���!�!com.macromates.caret{
column = 0;
line = 1;
}

@@ -1,4 +0,4 @@

Mac OS X  2��ATTR�{���"�"com.macromates.caret{
Mac OS X  2��ATTR�#���"�"com.macromates.caret{
column = 19;
line = 3;
}

@@ -1,4 +0,4 @@

Mac OS X  2��ATTR�{���"�"com.macromates.caret{
column = 0;
line = 43;
Mac OS X  2��ATTR�#���#�#com.macromates.caret{
column = 61;
line = 36;
}

@@ -1,4 +0,4 @@

Mac OS X  2��ATTR�{���"�"com.macromates.caret{
Mac OS X  2��ATTR�#���"�"com.macromates.caret{
column = 0;
line = 22;
line = 34;
}

@@ -1,4 +0,4 @@

Mac OS X  2��ATTR�{���"�"com.macromates.caret{
Mac OS X  2��ATTR�#���"�"com.macromates.caret{
column = 0;
line = 75;
line = 13;
}

@@ -1,4 +0,4 @@

Mac OS X  2��ATTR�{���"�"com.macromates.caret{
column = 0;
line = 11;
Mac OS X  2��ATTR�#���"�"com.macromates.caret{
column = 37;
line = 0;
}

@@ -1,1 +0,4 @@

Mac OS X  2��ATTR�{��� � com.macromates.caretx���R������<[k0?'3/«��
Mac OS X  2��ATTR�#���#�#com.macromates.caret{
column = 61;
line = 56;
}

@@ -8,3 +8,3 @@ var validator = require("validator"),

this.extend = function(func) {
this.add = function(func) {
stack.push(func);

@@ -29,3 +29,3 @@ return this;

var args = Array.prototype.slice.call(arguments);
return this.extend(function(value) {
return this.add(function(value) {
return FilterPrototype[name].apply(externalFilter.sanitize(value), args);

@@ -37,3 +37,3 @@ });

Filter.prototype.ifNull = function(replacement) {
return this.extend(function(value) {
return this.add(function(value) {
if (object.isUndefined(value) || value === null || value === '') {

@@ -47,3 +47,3 @@ return replacement;

Filter.prototype.toUpper = Filter.prototype.toUpperCase = function() {
return this.extend(function(value) {
return this.add(function(value) {
return value.toUpperCase();

@@ -54,3 +54,3 @@ });

Filter.prototype.toLower = Filter.prototype.toLowerCase = function() {
return this.extend(function(value) {
return this.add(function(value) {
return value.toLowerCase();

@@ -61,3 +61,3 @@ });

Filter.prototype.truncate = function(length) {
return this.extend(function(value) {
return this.add(function(value) {
if (value.length <= length) {

@@ -78,5 +78,5 @@ return value;

Filter.prototype.custom = function(func) {
return this.extend(func);
return this.add(func);
};
module.exports = Filter;

@@ -21,4 +21,12 @@ var validator = require("validator"),

["body", "query", "params"].forEach(function(source) {
if (req[source] && !object.isString(req[source])) {
Object.keys(req[source]).forEach(function(name) {
req.form[name] = req[source][name];
});
}
});
routines.forEach(function(routine) {
var result = routine.run(req.body);
var result = routine.run(req.form);

@@ -35,3 +43,3 @@ if (Array.isArray(result) && result.length) {

value: req.form.errors === undefined,
enumerable: true
enumerable: false
});

@@ -38,0 +46,0 @@

@@ -11,3 +11,3 @@ var validator = require("validator"),

this.extend = function(func) {
this.add = function(func) {
stack.push(func);

@@ -54,3 +54,3 @@ return this;

return this.extend(function(value) {
return this.add(function(value) {
if (typeof value == "undefined" || value === undefined) {

@@ -66,3 +66,3 @@ return value;

Validator.prototype.isNumeric = function(message) {
return this.extend(function(value) {
return this.add(function(value) {
if (object.isNumber(value) || (object.isString(value) && value.match(/^[-+]?[0-9]*\.?[0-9]+$/))) {

@@ -77,3 +77,3 @@ } else {

Validator.prototype.isDecimal = function(message) {
return this.extend(function(value) {
return this.add(function(value) {
if ((object.isNumber(value) && value % 1 == 0) || (object.isString(value) && value.match(/^[-+]?[0-9]*\.[0-9]+$/))) {

@@ -113,3 +113,3 @@ } else {

return this.extend(function(value) {
return this.add(function(value) {
if (pattern.test(value) === false) {

@@ -146,3 +146,3 @@ throw new Error(message || "Invalid characters");

return this.extend(function(value) {
return this.add(function(value) {
if (pattern.test(value) === true) {

@@ -155,3 +155,3 @@ throw new Error(message || "Invalid characters");

Validator.prototype.required = function(placeholderValue, message) {
return this.extend(function(value) {
return this.add(function(value) {
if (object.isUndefined(value) || value == null || value === '' || value == placeholderValue) {

@@ -163,4 +163,20 @@ throw new Error(message || "Missing value");

Validator.prototype.minLength = function(length, message) {
return this.add(function(value) {
if (value.toString().length < length) {
throw new Error(message || "Too short");
}
});
};
Validator.prototype.maxLength = function(length, message) {
return this.add(function(value) {
if (value.toString().length > length) {
throw new Error(message || "Too long");
}
});
};
Validator.prototype.custom = function(func, message) {
return this.extend(function(value) {
return this.add(function(value) {
try {

@@ -167,0 +183,0 @@ func(value);

{
"name": "express-form",
"description": "Form validation and data filtering for Express",
"version": "0.1.1",
"version": "0.2.0",
"homepage": "https://github.com/dandean/express-form",

@@ -6,0 +6,0 @@ "repository": {

@@ -30,8 +30,12 @@ Express Form provides data filtering and validation as route middleware to your Express applications.

// Express request handler now gets filtered and validated body
// Express request-handler now receives filtered and validated data
function(req, res){
// Now we can inspect the errors!
if (!req.form.isValid) {
// Handle errors
console.log(req.form.errors);
} else {
// Or, use filtered form data from the form object:
console.log("Username:", req.form.username);
console.log("Password:", req.form.password);
}

@@ -44,5 +48,245 @@ }

Coming soon! For now, just read the source.
### Module
The Express Form **module** returns an Express [Route Middleware](http://expressjs.com/guide.html#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");
app.post('/user',
// Express Form Route Middleware: trims whitespace off of
// the `username` field.
form(form.filter("username").trim()),
// standard Express handler
function(req, res) {
// ...
}
);
### Filters
The `filter` property of the module creates a filter object tied to a specific field.
filter(fieldname);
// -> Filter
The API is chainable, so you can keep calling filter methods one after the other:
filter("username").trim().toLower().truncate(5)
#### 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
ltrim(chars)
rtrim(chars)
toLower() / toLowerCase()
toUpper() / toUpperCase()
truncate(length) -> Chops value at (length - 3), appends `...`
Custom Filters
custom(function)
Filters the field value using custom logic.
Example:
If the `name` field has a value of "hello there", this would
transform it to "hello-there".
filter("name").custom(function(value) {
return value.replace(/\s+/g, "-");
});
### Validators
The `validate` property of the module creates a validator object tied to a specific field.
validate(fieldname[, label]);
// -> Validator
The API is chainable, so you can keep calling validator methods one after the other:
validate("username").required().isAlphanumeric()
#### 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:
validate("username").required()
// -> "Missing field"
validate("username").required("%s is a required field.")
// -> "username is a required field."
validate("username", "Username").required("%s is a required field.")
// -> "Username is a required field."
**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.
Example:
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.
Example:
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*
isNumeric([message])
isInt([message])
isDecimal([message])
isFloat([message])
notNull([message])
isNull([message])
*By Format*
isEmail([message])
isUrl([message])
isIP([message])
isAlpha([message])
isAlphanumeric([message])
isLowercase([message])
isUppercase([message])
*By Content*
notEmpty([message])
Checks if the value is not just whitespace.
equals( value [, message] )
- value (String): A value that should match the field value.
Compares the field to `value`.
Example:
validate("username").equals("admin")
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`.
*Other*
required([message])
Checks that the field is present in form data, and has a value.
custom(function[, message])
- function (Function): A custom validation function.
Validates the field using a custom validation function. If the function
throws, and `message` is not provided, the thrown error message is used.
Example:
validate("username").custom(function(value) {
if (value !== "admin") {
throw new Error("%s must be 'admin'.");
}
});
### http.ServerRequest.prototype.form
Express Form adds a `form` object with various properties to the request.
isValid -> Boolean
errors -> Array or undefined
// Example request handler:
function(req, res) {
if (req.isValid == false) {
console.log(req.errors);
}
}
Installation:

@@ -52,1 +296,7 @@ -------------

npm install express-form
Credits
-------
Currently, Express Form uses many of the validation and filtering functions provided by Chris O'Hara's [node-validator](https://github.com/chriso/node-validator).

@@ -8,11 +8,20 @@ TODO

* minLength and maxLength validators
* configurability
* Should params and query values get mixed in?
* Should data get pulled from all sources into form object? If so, precedence?
* body.id --> req.form.id
* url?page=5 --> req.form.page
* url/:page --> req.form.page
### request.form values
Precedence: url param -> query param -> request body
TODO: check how this compares to other solutions: rails, zend, django, .net.
TODO: how does this work with request.param() ? May need to override that so
to ensure that it pulls form request.form.
### Configurability
What configuration options should be available?
* Debugging?
* Default message overrides?
* Connection to express-contrib/flash?
* Auto-local each of the form props?
Testing and Compatibility

@@ -29,2 +38,3 @@ -------------------------

* Add notes on how to extend the filters and validators
* Add notes on how to extend the filters and validators
* Change node-validator toUppercase/toLowercase to use standard JS caps: toUpper**C**ase, toLower**C**ase.

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc