What is express-validator?
express-validator is a set of express.js middlewares that wraps validator.js, a library for string validation and sanitization. It provides a comprehensive set of validation and sanitization middlewares for handling user input in express applications.
What are express-validator's main functionalities?
Validation
This feature allows you to validate user input. In this example, the 'username' field must be alphanumeric and the 'password' field must be at least 5 characters long. If the validation fails, a 400 status code with the validation errors is returned.
const { body, validationResult } = require('express-validator');
app.post('/user', [
body('username').isAlphanumeric(),
body('password').isLength({ min: 5 })
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send('User is valid');
});
Sanitization
This feature allows you to sanitize user input. In this example, the 'email' field is normalized to a standard email format and the 'username' field is trimmed of whitespace and escaped to prevent HTML injection.
const { body } = require('express-validator');
app.post('/user', [
body('email').normalizeEmail(),
body('username').trim().escape()
], (req, res) => {
res.send('User input is sanitized');
});
Custom Validators
This feature allows you to create custom validation logic. In this example, the 'age' field must be at least 18. If the validation fails, a 400 status code with the validation errors is returned.
const { body, validationResult } = require('express-validator');
app.post('/user', [
body('age').custom(value => {
if (value < 18) {
throw new Error('Age must be at least 18');
}
return true;
})
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send('User is valid');
});
Other packages similar to express-validator
joi
Joi is a powerful schema description language and data validator for JavaScript. It allows you to create blueprints or schemas for JavaScript objects to ensure validation of key information. Compared to express-validator, Joi is more focused on schema-based validation and is not tied to express.js.
yup
Yup is a JavaScript schema builder for value parsing and validation. It is similar to Joi but is more lightweight and has a more modern API. Like Joi, Yup is not tied to express.js and can be used in various JavaScript environments.
validator
Validator is a library of string validators and sanitizers. It is the underlying library used by express-validator for its validation and sanitization functions. While it provides a comprehensive set of validation and sanitization functions, it does not provide middleware for express.js out of the box.
express-validator
An express.js middleware for
node-validator.
This is basically a copy of a gist by
node-validator author chriso.
Installation
npm install express-validator
Usage
var util = require('util'),
express = require('express'),
expressValidator = require('express-validator'),
app = express.createServer();
app.use(express.bodyParser());
app.use(expressValidator([options]));
app.post('/:urlparam', function(req, res) {
req.checkBody('postparam', 'Invalid postparam').notEmpty().isInt();
req.checkParams('urlparam', 'Invalid urlparam').isAlpha();
req.checkQuery('getparam', 'Invalid getparam').isInt();
req.sanitize('postparam').toBoolean();
var errors = req.validationErrors();
if (errors) {
res.send('There have been validation errors: ' + util.inspect(errors), 400);
return;
}
res.json({
urlparam: req.param('urlparam'),
getparam: req.param('getparam'),
postparam: req.param('postparam')
});
});
app.listen(8888);
Which will result in:
$ curl -d 'postparam=1' http://localhost:8888/test?getparam=1
{"urlparam":"test","getparam":"1","postparam":true}
$ curl -d 'postparam=1' http://localhost:8888/t1est?getparam=1
There have been validation errors: [
{ param: 'urlparam', msg: 'Invalid urlparam', value: 't1est' } ]
$ curl -d 'postparam=1' http://localhost:8888/t1est?getparam=1ab
There have been validation errors: [
{ param: 'getparam', msg: 'Invalid getparam', value: '1ab' },
{ param: 'urlparam', msg: 'Invalid urlparam', value: 't1est' } ]
$ curl http://localhost:8888/test?getparam=1&postparam=1
There have been validation errors: [
{ param: 'postparam', msg: 'Invalid postparam', value: undefined} ]
Middleware Options
####errorFormatter
function(param,msg,value)
The errorFormatter
option can be used to specify a function that can be used to format the objects that populate the error array that is returned in req.validationErrors()
. It should return an Object
that has param
, msg
, and value
keys defined.
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
Validation errors
You have two choices on how to get the validation errors:
req.assert('email', 'required').notEmpty();
req.assert('email', 'valid email required').isEmail();
req.assert('password', '6 to 20 characters required').len(6, 20);
var errors = req.validationErrors();
var mappedErrors = req.validationErrors(true);
errors:
[
{param: "email", msg: "required", value: "<received input>"},
{param: "email", msg: "valid email required", value: "<received input>"},
{param: "password", msg: "6 to 20 characters required", value: "<received input>"}
]
mappedErrors:
{
email: {
param: "email",
msg: "valid email required",
value: "<received input>"
},
password: {
param: "password",
msg: "6 to 20 characters required",
value: "<received input>"
}
}
Nested input data
Example:
<input name="user[fields][email]" />
Provide an array instead of a string:
req.assert(['user', 'fields', 'email'], 'valid email required').isEmail();
var errors = req.validationErrors();
console.log(errors);
Output:
[
{
param: "user_fields_email",
msg: "valid email required",
value: "<received input>"
}
]
Alternatively you can use dot-notation to specify nested fields to be checked:
req.assert(['user.fields.email'], 'valid email required').isEmail();
Regex routes
Express allows you to define regex routes like:
app.get(/\/test(\d+)/, function() {});
You can validate the extracted matches like this:
req.assert(0, 'Not a three-digit integer.').len(3, 3).isInt();
Extending
You can add your own validators using expressValidator.validator.extend(name, fn)
expressValidator.validator.extend('isFinite', function (str) {
return isFinite(str);
});
Changelog
v0.4.1
v0.4.0
- Added
req.checkBody()
(@zero21xxx). - Upgraded validator dependency to 1.1.3
v0.3.0
req.validationErrors()
now returns null
instead of false
if there are no errors.
v0.2.4
- Support for regex routes (@Cecchi)
v0.2.3
- Fix checkHeader() (@pimguilherme)
v0.2.2
- Add dot-notation for nested input (@sharonjl)
- Add validate() alias for check()
v0.2.1
- Fix chaining validators (@rapee)
v0.2.0
- Added
validationErrors()
method (by @orfaust) - Added support for nested form fields (by @orfaust)
- Added test cases
v0.1.3
v0.1.2
- Expose Filter and Validator instances to allow adding custom methods
v0.1.1
- Use req.param() method to get parameter values instead of accessing
req.params directly.
- Remove req.mixinParams() method.
v0.1.0
Contributors
- Christoph Tavan dev@tavan.de - Wrap the gist in an npm package
- @orfaust - Add
validationErrors()
and nested field support - @zero21xxx - Added
checkBody
function
License
Copyright (c) 2010 Chris O'Hara cohara87@gmail.com, MIT License