Introduction
Schema validation helps check if the data sent to your server is correct and safe before using it.
Jump into concepts and practice - no test required
Schema validation helps check if the data sent to your server is correct and safe before using it.
const schema = Joi.object({
name: Joi.string().required(),
age: Joi.number().integer().min(0)
});
const { error, value } = schema.validate(data);const schema = Joi.object({
email: Joi.string().email().required()
});const schema = Joi.object({
password: Joi.string().min(6).required()
});const schema = Joi.object({
age: Joi.number().integer().min(18).max(99)
});This Express server listens for POST requests to /register. It checks the request body against the userSchema. If the data is wrong, it sends back an error message. If correct, it confirms the data is valid.
import express from 'express'; import Joi from 'joi'; const app = express(); app.use(express.json()); const userSchema = Joi.object({ username: Joi.string().alphanum().min(3).max(30).required(), email: Joi.string().email().required(), age: Joi.number().integer().min(0).optional() }); app.post('/register', (req, res) => { const { error, value } = userSchema.validate(req.body); if (error) { return res.status(400).json({ error: error.details[0].message }); } res.json({ message: 'User data is valid', data: value }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Always validate data before using it to keep your app safe and stable.
Joi is a popular library for schema validation in Express apps.
Validation errors help users fix their input by showing clear messages.
Schema validation checks data matches rules before using it.
Use libraries like Joi to define and run these checks easily.
Validation improves app safety and user experience.
username?username must be a string and required, so use Joi.string().required().schema.validate(data) return?const schema = Joi.object({ age: Joi.number().min(18).required() });
const data = { age: 16 };app.post('/user', (req, res) => {
const schema = Joi.object({ email: Joi.string().email().required() });
const result = schema.validate(req.body.email);
if (result.error) {
res.status(400).send('Invalid email');
} else {
res.send('User created');
}
});phone that must be a string of 10 digits if present, and a required name string. Which Joi schema correctly enforces this?