Introduction
Input validation helps make sure the data your app gets is safe and correct. It stops bad or wrong data from causing problems.
Jump into concepts and practice - no test required
Input validation helps make sure the data your app gets is safe and correct. It stops bad or wrong data from causing problems.
app.post('/route', (req, res) => { const { name, age } = req.body; if (!name || typeof name !== 'string') { return res.status(400).send('Name is required and must be a string'); } if (age === undefined || typeof age !== 'number') { return res.status(400).send('Age is required and must be a number'); } // continue processing res.send('Data is valid'); });
app.post('/signup', (req, res) => { const { email } = req.body; if (!email || !email.includes('@')) { return res.status(400).send('Valid email is required'); } res.send('Signup data is valid'); });
app.post('/age-check', (req, res) => { const age = Number(req.body.age); if (!age || age < 18) { return res.status(400).send('You must be 18 or older'); } res.send('Age is valid'); });
This Express app listens for POST requests to '/register'. It checks if username is a string and password is at least 6 characters. If validation fails, it sends an error. Otherwise, it confirms the data is valid.
import express from 'express'; const app = express(); app.use(express.json()); app.post('/register', (req, res) => { const { username, password } = req.body; if (!username || typeof username !== 'string') { return res.status(400).send('Username is required and must be a string'); } if (!password || password.length < 6) { return res.status(400).send('Password is required and must be at least 6 characters'); } res.send('Registration data is valid'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Always validate input on the server, even if you check it on the client.
Use clear error messages to help users fix mistakes.
Input validation helps protect your app from security risks like injections.
Input validation keeps your app safe and working well.
Check data types and required fields before using input.
Send helpful error messages when input is wrong.
app.post('/submit', (req, res) => {
const age = req.body.age;
if (age < 18) {
res.send('Too young');
} else {
res.send('Welcome');
}
});