Open In App

How to implement validation in Express JS?

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:

npm install express express-validator
const express = require('express');
const { body, validationResult } = require('express-validator');
const app = express();
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!');
}
);
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

Example: Below is the example of validation in ExpressJS.






// 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;




// 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


Article Tags :