URL Slug Validation
Validates a URL-safe slug: lowercase letters, numbers, and hyphens only, no leading/trailing hyphens.
/^[a-z0-9]+(?:-[a-z0-9]+)*$/How it works
A URL slug is the human-readable part of a URL path (e.g., 'my-blog-post'). This pattern enforces lowercase alphanumeric characters with hyphens as separators. It prevents leading/trailing hyphens and consecutive hyphens via the non-capturing group structure.
Test Cases
Should Match
- my-blog-post
- hello-world-2024
- api-v2
Should NOT Match
- -leading-hyphen
- trailing-hyphen-
- UPPERCASE
- has spaces
Quick Summary
Validates URL slugs: lowercase letters and numbers separated by single hyphens, no leading or trailing hyphens. Used for blog post URLs, product pages, and any human-readable URL path segment.
Key Takeaways
- Only allows lowercase letters (a-z), digits (0-9), and hyphens
- Prevents leading hyphens, trailing hyphens, and consecutive hyphens
- Does not allow underscores, use a separate pattern if underscores are acceptable
- Slugs should be generated server-side from titles using a slugify function, not user-entered directly
When to use it
- Validating custom URL slugs in CMS or blog platforms
- Checking route parameters in Next.js or Express apps
- Enforcing naming conventions for API resource identifiers
Common Mistakes
- Allowing uppercase letters, slugs should always be lowercase for consistency
- Not slugifying user input before validation, use a library like 'slugify' to convert titles first
URL Slug Validation, Frequently Asked
How do I generate a slug from a title?
Use a slugify library: slugify('Hello World 2024') → 'hello-world-2024'. Libraries handle Unicode, accents, and special characters.
Should slugs be unique?
Yes. Enforce uniqueness at the database level with a unique index on the slug column.