使用 Joi/Express-Validator 验证输入
使用 Joi 或 express-validator 等强大库验证传入的请求数据,确保数据完整性。
使用 Joi/Express-Validator 验证输入 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Node.js Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Validate Inputs?
Input validation is a critical security and data integrity practice. It ensures that data received by your application is clean, correct, and safe to process.
Without proper validation, your application becomes vulnerable to:
- Security breaches: Like SQL injection or Cross-Site Scripting (XSS).
- Data corruption: Malformed data can break your application or database.
- Poor user experience: Inconsistent data leads to bugs and unexpected behavior.
Unvalidated Data: A Security Risk
Imagine a user submitting a form without validation. They could send:
- Empty fields: Required information is missing.
- Incorrect data types: A number field receives text.
- Malicious scripts: Code designed to exploit your system.
Validation acts as a gatekeeper, preventing bad data from entering your application's core.
Joi: Define Your Data Shape
Joi is a powerful schema description language and data validator for JavaScript. It allows you to define the structure, type, and constraints of your data using a clear, chainable API.
Think of a Joi schema as a blueprint for your expected data. Any data that doesn't match this blueprint will be flagged as invalid.
Joi Schema in Action
Here's a simple Joi schema for a user's name and age. Try running it to see how validation works. Remember to install Joi first (npm install joi).
const Joi = require('joi');
const userSchema = Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
age: Joi.number().integer().min(0).max(120).required()
});
async function runValidation() {
const validUser = { username: 'john_doe', age: 30 };
const invalidUser = { username: 'ab', age: 'twenty' };
console.log('--- Valid User Test ---');
try {
const value = await userSchema.validateAsync(validUser);
console.log('Validation successful for validUser!');
} catch (err) {
console.error('Validation failed for validUser:', err.details[0].message);
}
console.log('\n--- Invalid User Test ---');
try {
const value = await userSchema.validateAsync(invalidUser);
console.log('Validation successful for invalidUser!');
} catch (err) {
console.error('Validation failed for invalidUser:', err.details[0].message);
}
}
runValidation();Joi in an Express Route
To use Joi in an Express.js application, you typically create a middleware function that performs the validation before the route handler is executed. This keeps your route handlers clean and focused on business logic.
const express = require('express');
const Joi = require('joi');
const app = express();
const port = 3000;
app.use(express.json()); // For parsing application/json
const userSchema = Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
email: Joi.string().email().required(),
password: Joi.string().min(6).required()
});
// Middleware to validate request body using Joi
const validateUser = (req, res, next) => {
const { error } = userSchema.validate(req.body);
if (error) {
return res.status(400).send(error.details[0].message);
}
next(); // If validation passes, proceed to the route handler
};
app.post('/register', validateUser, (req, res) => {
// If we reach here, req.body is valid
res.status(201).send('User registered successfully!');
});
app.get('/', (req, res) => {
res.send('Server is running. Try POST to /register with JSON data.');
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
console.log('Try: POST http://localhost:3000/register with {\"username\":\"testuser\", \"email\":\"a@b.com\", \"password\":\"password123\"}');
console.log('Or with invalid data: {\"username\":\"ab\", \"email\":\"a@b.com\"}');
});Express-Validator: Middleware Power
Express-Validator is a set of Express.js middleware that wraps the powerful validator.js library. It focuses on validating and sanitizing data directly within the Express request cycle.
It's often favored for its seamless integration with Express routes, allowing you to chain multiple validation rules directly in your route definitions.
Express-Validator in Action
Here's how to use express-validator to validate an email and password directly within an Express route. Notice the check() function and validationResult(). Remember to install Express-Validator (npm install express-validator).
const express = require('express');
const { check, validationResult } = require('express-validator');
const app = express();
const port = 3000;
app.use(express.json());
app.post('/login', [
check('email', 'Email is required').notEmpty(),
check('email', 'Please include a valid email').isEmail(),
check('password', 'Password must be 6 or more characters').isLength({ min: 6 })
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// If we reach here, req.body is valid
res.send('User logged in successfully!');
});
app.get('/', (req, res) => {
res.send('Server is running. Try POST to /login with JSON data.');
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
console.log('Try: POST http://localhost:3000/login with {\"email\":\"user@example.com\", \"password\":\"password123\"}');
console.log('Or with invalid data: {\"email\":\"bademail\", \"password\":\"123\"}');
});Responding to Validation Errors
When validation fails, your API should return a clear, informative error message to the client. Both Joi and Express-Validator provide ways to extract these errors.
- Joi: The
errorobject containsdetailswith specific messages. - Express-Validator:
validationResult(req)aggregates all errors into an array, often including field names and messages.
Always return an appropriate HTTP status code, like 400 Bad Request, to indicate client-side input issues.
Joi vs. Express-Validator: Choose Wisely
Both libraries are excellent, but excel in different scenarios:
- Joi: Ideal for complex, nested data structures. Great for defining a strict schema for your entire data model, often used for DTO (Data Transfer Object) validation.
- Express-Validator: Perfect for quick, inline validation of request parameters (body, query, params) directly within your Express routes. Its middleware approach integrates seamlessly.
You can even use both! Joi for core data models, and Express-Validator for simpler route-specific checks.
Validation Check
Consider the following statements about input validation with Joi and Express-Validator:
Recap: Secure Your Inputs
Congratulations! You've learned the importance of input validation and how to implement it using two popular Node.js libraries:
- Joi: For defining robust, schema-based validation rules for complex data.
- Express-Validator: For lightweight, middleware-based validation directly within your Express routes.
Always validate incoming data to protect your application from vulnerabilities and ensure data integrity. Keep building secure and reliable APIs!
常见问题解答
「使用 Joi/Express-Validator 验证输入」课时是免费的吗?
是的 — 「使用 Joi/Express-Validator 验证输入」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
「使用 Joi/Express-Validator 验证输入」这节课中我会学到什么?
使用 Joi 或 express-validator 等强大库验证传入的请求数据,确保数据完整性。 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Node.js Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「使用 Joi/Express-Validator 验证输入」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 开发自定义 Express 中间件
- 全局错误处理策略
- 使用 Joi/Express-Validator 验证输入
- 使用 JWT 的身份验证中间件