Using express-validator
in Express.js can help you handle form inputs efficiently by validating and sanitizing user input. Here's a basic guide on how to use express-validator
:
-
Install Dependencies:
First, install
express-validator
along withexpress
if you haven't already.npm install express express-validator
-
Setup Express App:
Set up your Express.js application.
const express = require('express'); const { body, validationResult } = require('express-validator'); const app = express(); app.use(express.json()); app.use(express.urlencoded({ extended: true }));
-
Define Route and Validation Middleware:
Define a route for handling form submissions and use
express-validator
middleware to validate and sanitize form inputs.app.post('/submit-form', [ // Validate fields body('name').notEmpty().trim().escape(), body('email').isEmail().normalizeEmail(), body('age').isInt({ min: 18, max: 100 }), // Sanitize fields body('phoneNumber').optional().trim().escape(), ], (req, res) => { // Check for validation errors const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } // If validation passes, handle form submission // Retrieve sanitized inputs from req.body const { name, email, age, phoneNumber } = req.body; // Process the form data as needed res.send('Form submitted successfully!'); });
- Handling Validation Errors: If there are validation errors, you can return them to the client to display error messages.
- Use Validation Errors in Client Side: In your client-side code, you can handle the errors returned by the server and display appropriate messages to the user.
By using express-validator
, you can efficiently handle form inputs in your Express.js application by ensuring that the data is validated and sanitized before further processing. This helps prevent security vulnerabilities and ensures data integrity.