0
0
Expressframework~30 mins

Custom validation rules in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom Validation Rules in Express
📖 Scenario: You are building a simple Express server that accepts user registration data. You want to make sure the data is valid before saving it.
🎯 Goal: Create a custom validation rule in Express to check that the username is at least 5 characters long and the password contains at least one number.
📋 What You'll Learn
Create an Express app with a POST route /register
Add a custom validation function called isValidUsername that checks username length
Add a custom validation function called hasNumber that checks password contains a number
Use these custom validations in the route to validate incoming data
💡 Why This Matters
🌍 Real World
Custom validation rules help ensure user input is correct before processing, improving app reliability and user experience.
💼 Career
Backend developers often write custom validations in Express to enforce business rules and secure APIs.
Progress0 / 4 steps
1
Set up Express app and route
Create an Express app by importing express, calling express() to create app, and add a POST route /register with a callback that takes req and res.
Express
Need a hint?

Remember to import express and create the app before defining routes.

2
Add custom validation functions
Add two functions: isValidUsername that takes username and returns true if its length is 5 or more, and hasNumber that takes password and returns true if it contains at least one digit.
Express
Need a hint?

Use username.length >= 5 and a regular expression /\d/ to check for digits.

3
Use validations in the route
Inside the /register route, get username and password from req.body. Use isValidUsername(username) and hasNumber(password) to check validity. If either fails, respond with status 400 and message 'Invalid input'. Otherwise, respond with status 200 and message 'Registration successful'.
Express
Need a hint?

Remember to parse JSON body with express.json() middleware before accessing req.body.

4
Start the server
Add app.listen to start the server on port 3000 and log 'Server running on port 3000' when it starts.
Express
Need a hint?

Use app.listen(3000, () => { ... }) to start the server and log a message.