Const
// Valid URLs
const validUrls = [
'https://example.com',
'http://subdomain.example.org/path',
'https://api.service.com/v1/endpoint?param=value',
'https://cdn.example.com/images/avatar.jpg'
];
validUrls.forEach(url => {
const result = UrlSchema.parse(url);
console.log(`${url} is valid`);
});
// User profile with avatar URL validation
const UserProfileSchema = z.object({
name: z.string(),
email: EmailSchema,
avatarUrl: UrlSchema.optional(),
websiteUrl: UrlSchema.optional()
});
// Content with external resource validation
const LessonContentSchema = z.object({
title: z.string(),
description: z.string(),
videoUrl: UrlSchema.optional(),
audioUrl: UrlSchema.optional(),
externalResources: z.array(UrlSchema).optional()
});
// URL validation in API endpoints
router.post('/resources', validate({
body: z.object({
name: z.string(),
url: UrlSchema,
description: z.string().optional()
})
}), async (req, res) => {
const { name, url, description } = req.body; // URL is validated
const resource = await resourceService.create({ name, url, description });
res.status(201).json({ resource });
});
URL validation schema with format checking and length limits
Comprehensive URL validation schema that ensures URLs are properly formatted and safe for use throughout the application. The schema validates URL structure according to standard specifications while enforcing reasonable length limits to prevent abuse and ensure compatibility with various systems and storage mechanisms.
The validation uses Zod's built-in URL validation which checks for proper protocol specification, domain format, and overall URL structure. This ensures that URLs are valid and can be safely used for HTTP requests, redirects, and user interface display without causing errors or security vulnerabilities.
Security features include prevention of malicious URL injection through format validation, protection against excessively long URLs that could cause buffer overflow or denial-of-service conditions, and consistent validation that supports safe URL handling in various contexts including user-generated content and external service integrations.