Back to Express JS Course
Express JS Course
In Express JS, validation typically refers to ensuring that the data received from the client side (e.g., through forms or API requests) meets certain criteria or constraints. There are various ways to perform validation in Express JS, but one popular approach is to use middleware functions provided by libraries such as express-validator.
Lets install express-validator first npm install express-validator
Lets see an example where we need to perform validation for create user route.
index.mjs
import express from "express"; import { checkSchema, validationResult} from 'express-validator'; import { createUserValidationSchema } from './utils/validationSchemas.mjs'; const app = express(); const PORT = process.env.PORT || 5000; const mockUsers = [ { id: 1, name: 'Praveen', designation: 'Technical Architect', city: 'Hyderabad' }, { id: 2, name: 'Prasad', designation: 'Technical Lead', city: 'Bangalore' }, { id: 3, name: 'Anusha', designation: 'Lead Developer', city: 'Chennai' }, { id: 4, name: 'Ravi', designation: 'Developer', city: 'Hyderabad' }, { id: 5, name: 'Kiran', designation: 'Technical Lead', city: 'Hyderabad' }, ]; // Middleware to parse JSON bodies app.use(express.json()); // Middleware to log requests app.use((req, res, next) => { console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`); next(); }); // Route to add a new user app.post('/api/v1_0/users',checkSchema(createUserValidationSchema), (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const newUser = req.body; // Validate the incoming data if (!newUser.name || !newUser.designation || !newUser.city) { return res.status(400).send({ msg: 'Bad Request. Missing required fields' }); } // Assign a new ID to the new user newUser.id = mockUsers.length ? mockUsers[mockUsers.length - 1].id + 1 : 1; // Add the new user to the mockUsers array mockUsers.push(newUser); // Respond with the newly created user res.status(201).send({ user: newUser }); }); app.listen(PORT, () => console.log(`Running on Port ${PORT}`));
createUserValidationSchema.mjs
export const createUserValidationSchema = { name: { isLength: { options: { min: 5, max: 32, }, errorMessage: "name must be at least 5 characters with a max of 32 characters", }, notEmpty: { errorMessage: "name cannot be empty", }, isString: { errorMessage: "name must be a string!", }, }, designation: { notEmpty: true, }, city: { notEmpty: true, }, };
Now lets post a request with name less than 5 characters.
