How to implement validation in Express JS?
Last Updated :
14 Feb, 2024
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
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 =
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
const express = require( 'express' );
const {
body,
validationResult
} = require( 'express-validator' );
const cors = require( 'cors' );
const app = express();
app.use(express.json());
app.use(cors());
app.post( '/submit' ,
body( 'email' ).isEmail().normalizeEmail(),
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400)
.json({ errors: errors.array() });
}
const { email } = req.body;
res.send( 'Form submitted successfully!' );
}
);
const port = 4000;
app.listen(port,
() => {
console.log(
`Server is running on
http:
);
});
|
Start the server using the following command.
node server.js
Output:
Output
Share your thoughts in the comments
Please Login to comment...