0
0
Expressframework~30 mins

Manual validation patterns in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Manual validation patterns in Express
📖 Scenario: You are building a simple Express server that accepts user registration data. You want to manually check the data before saving it.
🎯 Goal: Create an Express route that manually validates the username and age fields from the request body. If validation passes, respond with success; otherwise, respond with an error message.
📋 What You'll Learn
Create an Express app with a POST route at /register
Manually check that username exists and is a string
Manually check that age exists and is a number greater than or equal to 18
Send a JSON response with { success: true } if valid
Send a JSON response with { success: false, error: 'message' } if invalid
💡 Why This Matters
🌍 Real World
Manual validation is common in backend servers to ensure data is correct before processing or saving.
💼 Career
Backend developers often write manual validation logic in Express to handle user input safely and provide clear error messages.
Progress0 / 4 steps
1
Set up Express app and import modules
Write code to import express, create an app with express(), and use express.json() middleware.
Express
Need a hint?

Use require('express') to import Express. Create the app by calling express(). Use app.use(express.json()) to parse JSON bodies.

2
Create POST route at /register
Add a POST route handler on app for path '/register' with parameters req and res.
Express
Need a hint?

Use app.post('/register', (req, res) => { ... }) to create the route.

3
Manually validate username and age
Inside the /register route, extract username and age from req.body. Check if username is a string and exists, and age is a number >= 18. If invalid, respond with res.json({ success: false, error: 'Invalid input' }) and return.
Express
Need a hint?

Use const { username, age } = req.body to get data. Check types with typeof. Use return res.json(...) to send error and stop.

4
Send success response and start server
If validation passes, respond with res.json({ success: true }). Then add app.listen(3000) to start the server on port 3000.
Express
Need a hint?

Send success with res.json({ success: true }). Start server with app.listen(3000).