DD
DevDash

Regex for Filename Validation — Safe File Names

Quick Answer: Safe filename regex: ^[a-zA-Z0-9][a-zA-Z0-9._-]{0,254}$. This blocks path traversal (../), null bytes, and OS-restricted characters (<>:"/\|?*). Always sanitize filenames from user input to prevent directory traversal and injection attacks.

FAQ

Which characters are forbidden in filenames?

Windows forbids: \ / : * ? " < > |. macOS forbids: / and :. Linux forbids: / and null byte. For cross-platform safety, use only letters, digits, dots, hyphens, and underscores.

How do I prevent path traversal attacks?

Strip or reject ../ and ..\ sequences. Use path.basename() to extract just the filename. Never concatenate user input directly into file paths.

Want API access + no ads? Pro coming soon.