Welcome to the world of Node.js! In this tutorial, we'll delve into a crucial aspect of web development: Input Validation and Sanitization. š
Before we dive in, let's understand why input validation and sanitization are essential in Node.js:
In Node.js, we can validate user inputs by checking their types. Here's a simple example:
function validateNumber(input) {
const number = parseInt(input);
if (Number.isNaN(number)) {
return false;
}
return true;
}š Note: The Number.isNaN() function checks if a value is not a number.
Validating email addresses can be complex, but we can use libraries like validator.js to simplify the process:
const validator = require('validator');
function validateEmail(email) {
return validator.isEmail(email);
}Sanitizing user inputs involves removing or escaping any potentially harmful characters to prevent security vulnerabilities.
Sanitizing HTML inputs can be achieved using libraries like DOMPurify. Here's an example:
const DOMPurify = require('dompurify');
function sanitizeHTML(html) {
return DOMPurify.sanitize(html);
}What does the `Number.isNaN()` function do?
Let's put our knowledge into action! Create a simple Node.js server that validates and sanitizes user input.
const express = require('express');
const app = express();
const validator = require('validator');
const DOMPurify = require('dompurify');
app.use(express.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.send(`
<form action="/validate" method="POST">
<label for="email">Email:</label>
<input type="text" name="email" id="email" />
<button type="submit">Submit</button>
</form>
`);
});
app.post('/validate', (req, res) => {
const email = req.body.email;
if (!validator.isEmail(email)) {
res.send('Please enter a valid email address.');
return;
}
const sanitizedEmail = DOMPurify.sanitize(email);
res.send(`Your email is: ${sanitizedEmail}`);
});
app.listen(3000, () => console.log('Server listening on port 3000'));In this example, we create a simple form that collects email addresses, validate and sanitize them using validator.js and DOMPurify, and display the sanitized email.
That's it for today! Practice these concepts and stay tuned for more lessons on Node.js. š”