Validation
Safe Filename Regex
When users name files or upload them, a strict filename rule prevents path tricks and odd characters. This pattern accepts a base name made of letters, digits, underscores and hyphens, followed by an optional extension of letters and digits after a single dot. Slashes, backslashes, spaces and leading dots are all rejected, so values like ../secret or .htaccess fail. That makes it a reasonable allow-list for names you will later join to a folder path. It does not block reserved Windows device names such as CON or NUL, so add a separate check if files are stored on Windows.
Pattern (JavaScript)
/^[A-Za-z0-9_-]+(\.[A-Za-z0-9]+)?$/Starts at the start of the line/string, then one of the characters A-Za-z0-9_-, one or more times, then a group (the character ".", then a letter or digit, one or more times), optionally (zero or one time), then the end of the line/string.
Examples
Matches
- ✓ report_2026.pdf
- ✓ notes
- ✓ my-file.txt
Does not match
- ✗ ../etc/passwd
- ✗ file name.txt
- ✗ a/b.txt
Try it
0 matches (JavaScript engine)
report_2026.pdf
notes
my-file.txt
../etc/passwd
file name.txt
a/b.txtCode in 8 languages
Converted automatically from the JavaScript pattern; language-specific notes are shown where the syntax or support differs.
JavaScript
const re = /^[A-Za-z0-9_-]+(\.[A-Za-z0-9]+)?$/g;
const text = "report_2026.pdf";
const matches = [...text.matchAll(re)].map((m) => m[0]);
console.log(matches);Python
import re
pattern = re.compile(r'^[A-Za-z0-9_-]+(\.[A-Za-z0-9]+)?$')
text = 'report_2026.pdf'
matches = [m.group(0) for m in pattern.finditer(text)]
print(matches)PHP
<?php
$pattern = '/^[A-Za-z0-9_-]+(\.[A-Za-z0-9]+)?$/';
$text = 'report_2026.pdf';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("^[A-Za-z0-9_-]+(\\.[A-Za-z0-9]+)?$");
String text = "report_2026.pdf";
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}Go
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^[A-Za-z0-9_-]+(\.[A-Za-z0-9]+)?$`)
text := "report_2026.pdf"
fmt.Println(re.FindAllString(text, -1))
}C#
using System;
using System.Text.RegularExpressions;
var pattern = new Regex(@"^[A-Za-z0-9_-]+(\.[A-Za-z0-9]+)?$");
var text = "report_2026.pdf";
foreach (Match m in pattern.Matches(text))
{
Console.WriteLine(m.Value);
}Rust
// Cargo.toml: regex = "1"
use regex::Regex;
fn main() {
let re = Regex::new(r"^[A-Za-z0-9_-]+(\.[A-Za-z0-9]+)?$").unwrap();
let text = "report_2026.pdf";
for m in re.find_iter(text) {
println!("{}", m.as_str());
}
}- Add regex = "1" under [dependencies] in Cargo.toml.
Ruby
pattern = /^[A-Za-z0-9_-]+(\.[A-Za-z0-9]+)?$/
text = 'report_2026.pdf'
matches = text.to_enum(:scan, pattern).map { Regexp.last_match[0] }
p matchesFrequently asked questions
- Does this stop path traversal attacks?
- It rejects slashes and dots at the start, which blocks the usual ../ tricks in the name itself. Still resolve the final path on the server and confirm it stays inside the upload folder.
- Why is only one extension allowed?
- Names like invoice.pdf.exe are a classic way to hide an executable. Allowing a single extension keeps the real file type visible.
- Are spaces in filenames really a problem?
- They work on modern systems but cause trouble in scripts and URLs. Replacing spaces with hyphens or underscores is the safer convention.