0
0
Node.jsframework~30 mins

Input validation and sanitization in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Input Validation and Sanitization in Node.js
📖 Scenario: You are building a simple Node.js server that accepts user input for a username and email. To keep the server safe and clean, you need to check that the input is valid and remove any unwanted characters.
🎯 Goal: Build a Node.js script that validates and sanitizes user input for username and email before using it.
📋 What You'll Learn
Create an object called userInput with keys username and email and exact values.
Add a variable called emailPattern to hold a regular expression for validating emails.
Use a function called sanitizeInput to clean the username by removing spaces and special characters.
Add a final check that uses emailPattern.test() to validate the email and store the result in isEmailValid.
💡 Why This Matters
🌍 Real World
Validating and cleaning user input is essential to prevent errors and security issues in web servers and applications.
💼 Career
Input validation and sanitization are key skills for backend developers, security engineers, and anyone working with user data.
Progress0 / 4 steps
1
Create the initial user input object
Create an object called userInput with these exact entries: username set to " user!name123 " and email set to "user@example.com".
Node.js
Need a hint?

Use const userInput = { username: " user!name123 ", email: "user@example.com" }.

2
Add email validation pattern
Add a variable called emailPattern and assign it a regular expression that matches a simple email format: one or more word characters, an @ symbol, one or more word characters, a dot, and two to four letters.
Node.js
Need a hint?

Use const emailPattern = /^\w+@\w+\.\w{2,4}$/; to match emails like user@example.com.

3
Sanitize the username input
Write a function called sanitizeInput that takes a string and returns it with all spaces and special characters removed, leaving only letters and numbers. Then create a variable cleanUsername by calling sanitizeInput with userInput.username.
Node.js
Need a hint?

Use str.replace(/[^a-zA-Z0-9]/g, '') to remove unwanted characters.

4
Validate the email input
Add a variable called isEmailValid that stores the result of testing userInput.email against emailPattern using emailPattern.test().
Node.js
Need a hint?

Use const isEmailValid = emailPattern.test(userInput.email); to check email validity.