Getting Started
express-validator is a set of express.js middlewares that wraps validator.js validator and sanitizer functions.
Installation
Install it using npm (make sure that you have Node.js 6 or newer):
npm install --save express-validator
Basic guide
It's recommended that you have basic knowledge of the express.js module before you go on with this guide.
Let's get started by writing a basic route to create a user in the database:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/user', (req, res) => {
User.create({
username: req.body.username,
password: req.body.password
}).then(user => res.json(user));
});
Then, you'll want to make sure that you validate the input and report any errors before creating the user:
// ...rest of the initial code omitted for simplicity.
const { check, validationResult } = require('express-validator/check');
app.post('/user', [
// username must be an email
check('username').isEmail(),
// password must be at least 5 chars long
check('password').isLength({ min: 5 })
], (req, res) => {
// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
User.create({
username: req.body.username,
password: req.body.password
}).then(user => res.json(user));
});
Voila! Now, whenever a request that includes invalid username
or password
fields
is submitted, your server will respond like this:
{
"errors": [{
"location": "body",
"msg": "Invalid value",
"param": "username"
}]
}
For all the available validators in express-validator (just like its options), take a look at validator.js docs here.
What's next
This completes the basic guide on getting started with express-validator.
You might want to continue reading about some of the more advanced features available: