How to implement validation in Express JS?
Last Updated :
28 Apr, 2025
Validation is an important process in Express JS which ensures that the data received by the server fulfills the specific requirements or rules before it is processed further. This process helps in maintaining the integrity, security, and reliability of web applications. ExpressJS provides various tools and middleware, such as those used for validation checks, for user input like form submissions or API requests.
Steps to implement validation in ExpressJS:
- Step 1: Install the package: To install the necessary package in your express app.
npm install express express-validator
- Step 2: Import Required Modules: Require the necessary modules in your Express application file.
const express = require('express');
const { body, validationResult } = require('express-validator');
- Step 3: Create an Express Application: Create an instance of an Express application.
const app = express();
- Step 4: Define Routes: Define routes in your application where validation is needed.
app.post('/submit',
// Example validation for email field
body('email').isEmail().normalizeEmail(),
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400)
.json({ errors: errors.array() });
}
// If validation passes, process the form
// ...
res.send('Form submitted successfully!');
}
);
- Step 5: Validate Input: Use validation middleware provided by
express-validator
to define validation rules for each field in your request body. - Step 6: Handle Validation Results: Check the result of validation using the
validationResult
()
function. If there are errors, handle them appropriately, such as sending a response with a 400 status code and the validation errors. - Step 7: Start the Server: Start the Express server to listen for incoming requests.
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Example: Below is the example of validation in ExpressJS.
JavaScript
// App.js
import React, { useState } from 'react';
import axios from 'axios';
function App() {
const [email, setEmail] = useState('');
const [errors, setErrors] = useState([]);
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response =
await axios.post('http://localhost:4000/submit', { email });
console.log(response.data);
alert('Form submitted successfully!');
} catch (error) {
if (error.response) {
setErrors(error.response.data.errors);
} else {
console.error('Error:', error.message);
}
}
};
return (
<div>
<h1>Submit Form</h1>
<form onSubmit={handleSubmit}>
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
name="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
<button type="submit">Submit</button>
</form>
{errors.length > 0 && (
<div>
<h2>Validation Errors:</h2>
<ul>
{errors.map((error, index) => (
<li key={index}>{error.msg}</li>
))}
</ul>
</div>
)}
</div>
);
}
export default App;
JavaScript
// server.js
const express = require('express');
const {
body,
validationResult
} = require('express-validator');
const cors = require('cors');
const app = express();
app.use(express.json());
app.use(cors()); // Add cors middleware
app.post('/submit',
body('email').isEmail().normalizeEmail(),
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400)
.json({ errors: errors.array() });
}
// If validation passes, process the form
// For example, save the data to a database
const { email } = req.body;
// Database saving code here...
res.send('Form submitted successfully!');
}
);
const port = 4000;
app.listen(port,
() => {
console.log(
`Server is running on
http://localhost:${port}`
);
});
Start the server using the following command.
node server.js
Output:
Output
Similar Reads
How to perform form validation in React? Form validation in React involves ensuring that the data entered into a form meets certain criteria before submission. In this, we will see the form validation in React.Pre-requisitesNodeJS and NPMReactJSReact useState hookHTML, CSS, and JavaScriptSteps to Create React Application And Installing Mod
4 min read
How to Add Form Validation In Next.js ? Forms play a crucial role in modern web applications by ensuring the accuracy and validity of data. NeÂxt.js, a versatile framework for building ReÂact applications, offers form validation that helps verify useÂr input against predefined criteÂria, provides immediate feedback, and enhances data qual
3 min read
How to Validate Data using express-validator Module in Node.js ? Validation in node.js can be easily done by using the express-validator module. This module is popular for data validation. There are other modules available in market like hapi/joi, etc but express-validator is widely used and popular among them.Steps to install express-validator module:Â Â You can
3 min read
How to get multiple requests with ExpressJS ? Express.js is the most powerful framework of the node.js. Express.js is a routing and Middleware framework for handling the different routing of the webpage, and it works between the request and response cycle. Express.js use different kinds of middleware functions in order to complete the different
2 min read
Validating Date Inputs with express-validator in Node.js In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In some cases, we want the user to type a date that must come after some given d
5 min read