Const
// Valid email addresses
const validEmails = [
'user@example.com',
'test.email+tag@domain.co.uk',
'user123@subdomain.example.org',
'firstname.lastname@company-name.com'
];
validEmails.forEach(email => {
const result = EmailSchema.parse(email);
console.log(`${email} is valid`);
});
// User registration with email validation
const RegistrationSchema = z.object({
email: EmailSchema,
password: z.string().min(8),
confirmEmail: EmailSchema
}).refine(data => data.email === data.confirmEmail, {
message: 'Email addresses must match',
path: ['confirmEmail']
});
// Email update endpoint
router.put('/profile/email', validate({
body: z.object({ newEmail: EmailSchema })
}), async (req, res) => {
const { newEmail } = req.body; // Validated email address
await userService.updateEmail(req.user.id, newEmail);
res.json({ message: 'Email updated successfully' });
});
Email address validation schema with comprehensive format checking
Robust email validation schema that ensures email addresses conform to standard format requirements while preventing common email-based attacks and data integrity issues. The schema validates both the structural format of email addresses and enforces reasonable length limits to prevent abuse and ensure compatibility with database storage and email service providers.
The validation uses Zod's built-in email validation which implements RFC 5322 compliant email format checking, ensuring that email addresses are properly structured with valid local and domain parts. The maximum length limit of 255 characters aligns with email standards and prevents potential buffer overflow attacks or database storage issues.
Security features include prevention of email injection attacks through format validation, protection against excessively long email addresses that could cause denial-of-service conditions, and consistent validation that supports email verification workflows and authentication systems. The schema maintains compatibility with international email addresses and various domain formats.