Request Validation in Node.js
Learn how to validate incoming API requests in Node.js and Express before processing or saving data.
Request validation means checking whether the data sent by a client is valid and follows the rules required by the application. A REST API should not blindly accept every request.
For example, when a client creates a product, the API may require a product name and a valid, non-negative price. If the client sends an empty name or an invalid price, the server should reject the request.
1. What Is Request Validation?
Request validation is the process of checking request data against predefined rules. These rules help ensure that the API receives the expected data types, required fields, and acceptable values.
Suppose an API expects the following product data:
{
"name": "Laptop",
"price": 50000
}
The request may be rejected if the client sends invalid data:
{
"name": "",
"price": -500
}
In this example, the product name is empty and the price is negative. The API should return a validation error instead of accepting the data.
2. Why Is Request Validation Important?
Request validation helps an API to:
- Prevent invalid data from entering the application.
- Ensure required fields are provided.
- Check whether values have the correct data types.
- Return meaningful error messages to clients.
- Reduce unexpected errors during processing.
- Apply business rules consistently.
3. Basic Request Validation in Express
We can validate request data using JavaScript conditions. For example, we can check whether a name is a non-empty string and whether a price is a valid, non-negative number.
const express = require('express');
const app = express();
app.use(express.json());
app.post('/api/products', (req, res) => {
const { name, price } = req.body;
if (
typeof name !== 'string' ||
name.trim() === ''
) {
return res.status(400).json({
message: 'Product name is required'
});
}
if (
typeof price !== 'number' ||
!Number.isFinite(price) ||
price < 0
) {
return res.status(400).json({
message: 'Price must be a non-negative number'
});
}
res.status(201).json({
message: 'Product data is valid',
product: {
name: name.trim(),
price
}
});
});
app.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
In this example:
express.json()parses incoming JSON request bodies.req.bodyprovides the parsed request data.typeofchecks the data type.trim()removes whitespace from the beginning and end of a string.res.status(400).json()returns a validation error.res.status(201).json()indicates successful resource creation.
4. Validating Required Fields
Some fields must be present in a request. If a required field is missing or empty, the server should return a clear error message.
const { name, price } = req.body;
if (!name || typeof name !== 'string' || name.trim() === '') {
return res.status(400).json({
message: 'Name is required'
});
}
if (price === undefined) {
return res.status(400).json({
message: 'Price is required'
});
}
The first condition checks whether the name is missing, is not a string, or contains only whitespace. The second condition checks whether the price field was supplied.
5. Validating Data Types and Values
An API should verify both the data type and the allowed value range. For example, a product price should be a finite number and should not be negative.
if (
typeof price !== 'number' ||
!Number.isFinite(price) ||
price < 0
) {
return res.status(400).json({
message: 'Price must be a valid non-negative number'
});
}
Consider these values:
| Value | Valid? | Reason |
|---|---|---|
50000 |
Yes | Finite number greater than zero |
0 |
Yes | Zero is allowed by this validation rule |
-500 |
No | Negative price |
"50000" |
No | String instead of a number |
null |
No | Not a number |
6. Using a Validation Library
For larger applications, writing every validation rule manually can
become difficult. Libraries such as express-validator
provide reusable validation and error-checking methods.
Install the package using the terminal:
npm install express-validator
Example of validating product data:
const express = require('express');
const {
body,
validationResult
} = require('express-validator');
const app = express();
app.use(express.json());
app.post(
'/api/products',
[
body('name')
.isString()
.withMessage('Name must be a string')
.bail()
.trim()
.notEmpty()
.withMessage('Name is required'),
body('price')
.isFloat({ min: 0 })
.withMessage('Price must be a non-negative number')
],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array()
});
}
res.status(201).json({
message: 'Product data is valid',
product: req.body
});
}
);
app.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
In this example:
body('name')defines validation rules for the name field.body('price')defines validation rules for the price field.validationResult(req)collects validation errors.errors.isEmpty()checks whether validation failed.- The API returns status 400 when validation errors exist.
7. Request Validation Flow
Request validation takes place before the application performs the main operation.
Sends an API request
Parses the incoming request body
Checks required fields, types, and values
Return 400 Bad Request with error details
Continue to the application logic
Returns the result to the client
8. Testing Request Validation in Postman
Start the server and use Postman to send a POST request. Select the Body tab, choose raw, and select JSON.
node app.js
Configure the request:
| Setting | Value |
|---|---|
| Method | POST |
| URL | http://localhost:3000/api/products |
| Body type | raw JSON |
Example of valid request data:
{
"name": "Laptop",
"price": 50000
}
Expected response with status code 201 Created:
{
"message": "Product data is valid",
"product": {
"name": "Laptop",
"price": 50000
}
}
Now test with invalid data:
{
"name": "",
"price": -500
}
The basic validation example returns status code 400 Bad Request because the name is empty and the price is negative.
{
"message": "Product name is required"
}
The basic example returns the first validation error it encounters. The library-based example can return multiple validation errors together.
9. Common HTTP Status Codes
| Status Code | Meaning | Usage |
|---|---|---|
| 200 OK | Request completed successfully | Used for successful operations that return a response. |
| 201 Created | Resource created successfully | Commonly returned after successful resource creation. |
| 400 Bad Request | Request data is invalid | Used when validation rules fail. |
| 401 Unauthorized | Authentication is required or invalid | Used when the client is not properly authenticated. |
| 403 Forbidden | Access is not allowed | Used when the client lacks permission. |
| 404 Not Found | Resource does not exist | Used when a requested resource cannot be found. |
Important Points to Remember
- Request validation checks incoming data before processing it.
- Use
express.json()to parse JSON request bodies. - Use
req.bodyto access parsed body data. - Check required fields and expected data types.
- Validate value ranges according to business rules.
- Return 400 Bad Request when request data is invalid.
- Libraries such as
express-validatorhelp organize validation rules. - Validation does not replace authentication or authorization.
- Never assume client-provided data is automatically safe or valid.
Summary
Request validation is an important part of REST API development. It checks whether incoming data follows the application's rules before the server processes it. Express applications can use JavaScript conditions or libraries such as express-validator to validate fields, data types, and allowed values.
With this lesson, the basic REST API topics are complete: GET, POST, PUT, PATCH, DELETE, and request validation.