OWASP Guidance for Regex Input Validation
How the OWASP input validation cheat sheet treats regular expressions: allowlists, anchoring, ReDoS, Unicode pitfalls, and when a parser beats a pattern.
What the OWASP guidance covers
OWASP's Input Validation Cheat Sheet treats regular expressions as one tool for syntactic validation, which checks that data has the expected shape. It separates this from semantic validation, which checks that a value makes sense in context, such as a start date that falls before an end date. Its core advice is to validate on the server, to define what is allowed (an allowlist) rather than trying to list everything that is forbidden (a denylist), and to treat validation as a supporting control rather than the main defense against injection. This review covers how that guidance applies when you write and test regex patterns. Cheat sheets are revised over time, so check the current version before treating any detail here as final.
Is a regex the right check for your input?
A regex works well for inputs with a small, fixed format: postal codes, numeric identifiers, enumerated codes, or usernames limited to a defined character set. For these, an anchored allowlist pattern with an explicit length limit is clear and easy to test. The main tradeoff is between strictness and real-world variety. A pattern strict enough to reject bad input can also reject legitimate values, especially names, addresses, and international text.
Avoid a regex, or use it only as a rough first filter, in these cases:
- Email addresses: the cheat sheet recommends light syntactic checks followed by confirming the address, for example by sending a verification message, rather than one elaborate pattern.
- URLs, dates, and numbers with ranges: a dedicated parser or type conversion followed by range checks is more reliable than a pattern.
- Free-form text such as comments or names: restricting characters here mostly rejects legitimate users. Length limits and correct output encoding matter more.
- Structured formats such as JSON, XML, or HTML: validate them with a parser or schema, not a regex.
What validation changes and what it does not
A validation regex does not transform anything. It accepts or rejects the input, and the stored characters stay exactly as submitted. Changes happen only in steps you add around the check, such as trimming whitespace, Unicode normalization, or canonicalizing encoded input. The guidance is to normalize or canonicalize before you validate. Otherwise a value can pass the check in one form and be interpreted differently later. Whatever form you validate should be the form you store and use. If you validate a normalized copy but keep the raw original, the check no longer describes the data you actually hold.
Writing the pattern: anchors, allowlists and length
The most common mistake is an unanchored pattern. Without anchors, a pattern that matches a valid substring accepts any input that merely contains one, so "12345; anything else" would pass a ZIP code check. The cheat sheet stresses anchoring the full input. The details depend on the regex engine.
// JavaScript: without the m flag, ^ and $ anchor the whole string
const zip = /^[0-9]{5}(?:-[0-9]{4})?$/;
zip.test(value);
# Python: fullmatch requires the entire string to match
import re
re.fullmatch(r"[0-9]{5}(?:-[0-9]{4})?", value)
Engine differences to check:
- In Python and PCRE, $ also matches just before a trailing newline. A pattern like ^[0-9]{5}$ used with re.match can therefore accept "12345\n". Use fullmatch, or \A and \z where the engine supports them.
- In Python 3 string patterns and in .NET, \d matches digits from other scripts as well as 0-9. In JavaScript, \d matches only ASCII digits. Writing [0-9] makes the intent explicit in every engine.
- Always bound quantifiers. Use {5} or {1,64} instead of + or * when the field has a known maximum, and check length before running the pattern.
Regular expression denial of service
Backtracking engines, which include the default engines in JavaScript, Python, Java, and .NET, can take exponential time on some patterns when the input almost matches. OWASP calls this ReDoS. The classic warning sign is a nested quantifier or overlapping alternation.
Risky pattern: ^(a+)+$
Trigger input: aaaaaaaaaaaaaaaaaaaaaaaaaaaa!
Mitigations are to avoid nested or overlapping quantifiers, enforce a length limit before matching, use a match timeout where the platform offers one (.NET supports this), or use a linear-time engine such as RE2 or Rust's regex crate when its feature set is enough. This review includes no timing measurements. Test any pattern exposed to untrusted input in your own engine with near-miss inputs.
Unicode, copied text and display
Text pasted from documents, chat apps, or web pages often carries characters the user cannot see: non-breaking spaces, zero-width characters, and bidirectional control characters. A strict ASCII allowlist will reject these, which is safe but can puzzle users whose input looks correct. A permissive pattern may accept them and store a value that displays differently from what it contains.
Bidirectional controls such as the right-to-left override do not change the stored character order. They change only how the text is displayed, so part of a string can appear reversed on screen while the underlying characters stay in their original order. A validator sees the stored order, a reviewer sees the displayed order, and the two can disagree. Lookalike characters from different scripts cause a similar gap: two strings can look identical and still fail an equality check.
Practical steps:
- Decide on a normalization form, such as NFC or NFKC, and apply it before validation.
- Explicitly reject or strip bidirectional control and zero-width characters in fields where they have no legitimate use.
- For identifiers that must be unique, such as usernames, consider confusable-character checks in addition to the regex.
- In error messages, say which characters are allowed instead of only saying the input is invalid.
How a particular screen reader, search index, or destination app handles these characters is not covered by the material available for this review. Verify against that product's documentation or with a scoped test rather than assuming one result applies everywhere.
Validation is not output safety
OWASP is explicit that input validation does not replace context-appropriate defenses. SQL injection is prevented primarily with parameterized queries, and cross-site scripting primarily with output encoding for the specific context, such as HTML body, attribute, or JavaScript. A field that legitimately allows apostrophes or angle brackets, such as a surname or a code snippet, must still be handled safely downstream. Validation narrows what reaches those layers, but it is not a reason to skip them.
Gaps in this review
No test results, version history, or tool-specific evidence were supplied for this review. Statements about OWASP describe the general, widely documented direction of its input validation guidance, not a specific dated revision. Statements about regex engines reflect their documented behavior, and you should confirm them against the documentation for the versions you run. Accessibility and cross-application rendering of unusual Unicode input remain unverified here.