Learn how to validate any data entered as input in the Express endpoint
Assuming you have a POST endpoint that can accept name, email, and age parameters:
const express = require('express')
const app = express()
app.use(express.json())
app.post(’/form’, (req, res) => {
const name = req.body.name
const email = req.body.email
const age = req.body.age
})
How to perform server-side verification of these results to ensure:
- Is the name a string of at least 3 characters?
- Is the email a real email?
- Is age a number, between 0 and 110?
The best way to handle validation of any input from outside in Express is to useexpress-validator
package:
npm install express-validator
do you needcheck
withvalidationResult
Objects in the package:
const { check, validationResult } = require('express-validator');
We pass an arraycheck()
Call as the second parameterpost()
call. Everycheck()
call accepts parameter names as parameters. Then we callvalidationResult()
Verify that there are no verification errors. If so, we tell customers:
app.post('/form', [
check('name').isLength({ min: 3 }),
check('email').isEmail(),
check('age').isNumeric()
], (req, res) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() })
}
const name = req.body.name
const email = req.body.email
const age = req.body.age
})
Note i used
isLength()
isEmail()
isNumeric()
There are many more of these methods, all fromValidator.js, Including:
contains()
, Check whether the value contains the specified valueequals()
To check if the value is equal to the specified valueisAlpha()
isAlphanumeric()
isAscii()
isBase64()
isBoolean()
isCurrency()
isDecimal()
isEmpty()
isFQDN()
, Is it a fully qualified domain name?isFloat()
isHash()
isHexColor()
isIP()
isIn()
, Please check if the value is in the array of allowed valuesisInt()
isJSON()
isLatLong()
isLength()
isLowercase()
isMobilePhone()
isNumeric()
isPostalCode()
isURL()
isUppercase()
isWhitelisted()
, Check the input against the whitelist of allowed characters
You can use regular expressions to validate the inputmatches()
.
Can use inspection date
isAfter()
, Check if the entered date is after the date you passedisBefore()
To check if the entered date is before the date you passedisISO8601()
isRFC3339()
For exact details on how to use these validators, please seehttps://github.com/chriso/validator.js#validators.
All these checks can be combined in the following ways:
check('name')
.isAlpha()
.isLength({ min: 10 })
If there are any errors, the server will automatically send a response to convey the error. For example, if the email is invalid, the following will be returned:
{
"errors": [{
"location": "body",
"msg": "Invalid value",
"param": "email"
}]
}
You can use the following command to override this default error for each inspection:withMessage()
:
check('name')
.isAlpha()
.withMessage('Must be only alphabetical chars')
.isLength({ min: 10 })
.withMessage('Must be at least 10 chars long')
What if you want to write your own special custom validator? you can use itcustom
Validator.
In the callback function, you can reject verification by raising an exception or returning a rejected promise:
app.post('/form', [
check('name').isLength({ min: 3 }),
check('email').custom(email => {
if (alreadyHaveEmail(email)) {
throw new Error('Email already registered')
}
}),
check('age').isNumeric()
], (req, res) => {
const name = req.body.name
const email = req.body.email
const age = req.body.age
})
Custom validator:
check('email').custom(email => {
if (alreadyHaveEmail(email)) {
throw new Error('Email already registered')
}
})
Can be rewritten as
check('email').custom(email => {
if (alreadyHaveEmail(email)) {
return Promise.reject('Email already registered')
}
})
Download mine for freeExpress.js manual
More crash tutorials:
- Express, the popular Node.js framework
- Use Express to retrieve GET query string parameters
- Use express-validator to validate input in Express
- Express template
- Use Express to serve static assets
- Send JSON response using Express
- Fast meeting
- Send a reply using Express
- Send files using Express
- Use Express-Validator to clean up the input in Express
- Route in Express
- Express HTTPS server with self-signed certificate
- Express, request parameters
- Use Express to retrieve POST query parameters
- Use Express to handle redirects
- Fast middleware
- Set up let's encrypt for Express
- Use HTTP headers in Express
- Processing forms in Express
- Use Express to process file uploads in forms
- Processing CORS in Express
- Use Express to manage cookies