دوره‌ها / Node.js / Validation (Input Validation)

Validation (Input Validation)

15 دقیقه Article

Validation: اعتبارسنجی ورودی ✅

Input Validation برای اطمینان از صحت داده‌های ورودی ضروریه!

استفاده از express-validator:

// نصب
// npm install express-validator

const { body, validationResult } = require('express-validator');

// Validation rules
const validateUser = [
    body('name').trim().isLength({ min: 3 }).withMessage('Name must be at least 3 characters'),
    body('email').isEmail().withMessage('Invalid email'),
    body('password').isLength({ min: 8 }).withMessage('Password must be at least 8 characters')
];

// استفاده
app.post('/users', validateUser, (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }
    
    // Continue with valid data
    res.json({ message: 'User created' });
});

Custom Validation:

// Custom validator
body('email').custom(async (value) => {
    const user = await User.findOne({ email: value });
    if (user) {
        throw new Error('Email already exists');
    }
})
✅ یاد گرفتید: Validation برای امنیت و data integrity ضروریه!

آماده رفتن به درس بعدی هستید؟

این درس را به پایان رساندید و می‌توانید به درس بعدی بروید.

برای ذخیره پیشرفت وارد شوید