87 lines
2.1 KiB
JavaScript
87 lines
2.1 KiB
JavaScript
const { body, validationResult } = require('express-validator');
|
|
|
|
/**
|
|
* Validation middleware for user registration
|
|
*/
|
|
exports.validateRegistration = [
|
|
body('username')
|
|
.trim()
|
|
.notEmpty()
|
|
.withMessage('Username is required')
|
|
.isLength({ min: 3, max: 50 })
|
|
.withMessage('Username must be between 3 and 50 characters')
|
|
.matches(/^[a-zA-Z0-9_]+$/)
|
|
.withMessage('Username can only contain letters, numbers, and underscores'),
|
|
|
|
body('email')
|
|
.trim()
|
|
.notEmpty()
|
|
.withMessage('Email is required')
|
|
.isEmail()
|
|
.withMessage('Please provide a valid email address')
|
|
.normalizeEmail(),
|
|
|
|
body('password')
|
|
.notEmpty()
|
|
.withMessage('Password is required')
|
|
.isLength({ min: 8 })
|
|
.withMessage('Password must be at least 8 characters long')
|
|
.matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/)
|
|
.withMessage('Password must contain at least one uppercase letter, one lowercase letter, and one number'),
|
|
|
|
body('guestSessionId')
|
|
.optional()
|
|
.trim()
|
|
.notEmpty()
|
|
.withMessage('Guest session ID cannot be empty if provided'),
|
|
|
|
// Check for validation errors
|
|
(req, res, next) => {
|
|
const errors = validationResult(req);
|
|
if (!errors.isEmpty()) {
|
|
return res.status(400).json({
|
|
success: false,
|
|
message: 'Validation failed',
|
|
errors: errors.array().map(err => ({
|
|
field: err.path,
|
|
message: err.msg
|
|
}))
|
|
});
|
|
}
|
|
next();
|
|
}
|
|
];
|
|
|
|
/**
|
|
* Validation middleware for user login
|
|
*/
|
|
exports.validateLogin = [
|
|
body('email')
|
|
.trim()
|
|
.notEmpty()
|
|
.withMessage('Email is required')
|
|
.isEmail()
|
|
.withMessage('Please provide a valid email address')
|
|
.normalizeEmail(),
|
|
|
|
body('password')
|
|
.notEmpty()
|
|
.withMessage('Password is required'),
|
|
|
|
// Check for validation errors
|
|
(req, res, next) => {
|
|
const errors = validationResult(req);
|
|
if (!errors.isEmpty()) {
|
|
return res.status(400).json({
|
|
success: false,
|
|
message: 'Validation failed',
|
|
errors: errors.array().map(err => ({
|
|
field: err.path,
|
|
message: err.msg
|
|
}))
|
|
});
|
|
}
|
|
next();
|
|
}
|
|
];
|