You check a string for invalid input by defining what "valid" means first, then applying cheap structural checks before expensive semantic ones, and normalizing deliberately at a known point. The key condition is that validation must match the destination: a value can be fine for a display name and invalid for a SQL identifier or a filename. So the rest of this guide works through the checks in the order you should run them, with the failure modes each one catches and the ones it misses.
String validation is one of those tasks where almost everyone starts with a regular expression and later regrets it. The regex grows, the edge cases multiply, and eventually someone pastes in a lookbehind that only two people on the team can read. A layered approach keeps individual rules simple, makes errors easier to explain to users, and lets you stop before running expensive checks on input that's already doomed.
Start By Writing the Contract, Not the Code
Before any loop or pattern, write down five things about each field: the character set allowed, the length bounds, whether surrounding whitespace is meaningful, the canonical form you'll store, and what the field feeds into downstream. That last item drives most of the real decisions. A username that lands in a URL path has different constraints than one that only appears in a UI list.
Three rules keep contracts honest. First, specify length in characters or bytes explicitly, because they diverge the moment non-ASCII text appears. Second, define whether empty and absent are the same; an empty text box and a missing parameter usually mean different things. Third, name the acceptance test for every rule, so validation is testable rather than aspirational.
A short written contract also prevents the most common bug in this space: validating something that isn't the thing you use. If you check a trimmed copy but query the untrimmed original, you've validated a value that never reaches the database.
Establish Encoding and Length Boundaries Early
The first checks are the cheapest and catch a surprising share of bad input.
Encoding. Most modern runtimes (Python 3, Java, Go, Rust, JavaScript's string type) represent text as Unicode, but input arrives as bytes. Decode at the boundary and reject invalid sequences there rather than letting replacement characters sneak in. Python raises UnicodeDecodeError on invalid UTF-8 by default; catch it and return a clear failure instead of silently substituting U+FFFD.
Byte length before character length. Databases differ on whether VARCHAR(50) means 50 characters or 50 bytes. PostgreSQL counts characters; MySQL's VARCHAR limit is in characters but the row size limit is in bytes. A 20-character string of emoji can exceed 50 bytes easily. Validate against the storage constraint, not just the apparent one.
Lookalike and control characters. Reject or normalize invisible characters at this stage: zero-width spaces, bidirectional overrides, and stray control characters below U+0020 except tab, newline, and carriage return where the field permits them. These are the characters that make a string look identical on screen yet compare differently.
Normalize Before You Validate, Never After
Normalization is a transformation: NFC/NFD form for Unicode, trimming, collapsing internal runs of whitespace, lowercasing for comparison. The mistake is normalizing in the UI layer and validating in the server layer, so the stored value never matched either check.
For Unicode specifically, é as a single code point versus e plus a combining accent renders the same but hashes differently. That matters for duplicate detection (two visually identical usernames) and for comparison (a password or token that fails a byte-equality test despite looking correct). Normalize with NFC for storage and comparison unless you have a reason not to. Python's unicodedata.normalize('NFC', s) and Java's Normalizer.normalize(s, Form.NFC) do the job.
Trimming deserves a decision, not a default. Leading and trailing spaces are user noise for a name field, but they can be significant inside identifiers, quoted strings, and code. Decide per field, document it, and apply it once at the boundary.
Run Structural Checks: Presence, Length, Type of Content
These checks confirm the value has the shape you expect before you look at its meaning.
1: Presence. Distinguish null from empty. NULL means "not provided"; "" means "provided as empty." Your contract says which fields permit each. 2: Length bounds. Check minima and maxima after normalization and in the correct unit (characters versus bytes, codepoints versus grapheme clusters). A "maximum 100 characters" rule based on codepoints will reject some valid emoji sequences that users believe are one character. 3: Content class. Confirm the string contains only the character classes it should: digits for a numeric ID, decimal digits plus one separator for a price, printable letters for a name. Iterate codepoints rather than using isalpha()-style checks if you need precise control, because those helpers vary across languages. In Python, str.isalpha() is True for many scripts beyond Latin; that's correct for a name field and wrong for an ASCII-only identifier. 4: Character set. For identifiers intended to be ASCII-safe, reject or map anything outside the target set. This is where the regex ^[A-Za-z0-9_]+$ earns its keep, and where it should stay: a plain allowlist over a known set, not an attempt to describe grammar.
Success here looks like a value that's the right shape. Check it by running your normalizer first, then re-testing the normalized value. If normalization changes length or content, your tests need to include the before-and-after forms.
Validate Syntax: Formats, Patterns, and Parsers
Format validation asks whether a string matches a known structure: email, phone number, date, currency, postal code, IP address. The general principle is to use the narrowest tool that expresses the rule.
Dates: use a parser with an explicit format, not a regex. Python's datetime.strptime(s, "%Y-%m-%d") rejects February 30 and accepts only zero-padded values; a regex accepts the same digits but silently waves through February 30. If you need locality, parse time zones explicitly rather than relying on the server's default. Email: full RFC 5322 backtracking regexes are unmaintainable. A common practical rule is "one @, at least one character either side, dot in the domain, length under 254 bytes." That rejects some technically valid addresses and accepts some deliverable-but-odd ones, which is the right trade-off for most products. Deliverability ultimately requires a confirmation email. Numbers: if you need integers, parse them with an explicit base and reject trailing garbage. int("12abc") fails in Python but parseInt("12abc") returns 12 in JavaScript. Use strict parse functions or validate the whole string first. IP addresses, URLs, and IDs: use the standard library's parser where one exists. In Go, net.ParseIP and net/url handle the cases you'd get wrong by hand.
A worked example is worth the space. Suppose you need a "duration" field in the format HH:MM. A regex ^\d{2}:\d{2}$ accepts 99:99. A split-and-parse step then checks 0 <= minutes < 60 and a maximum hour cap. The lesson generalizes: use regex for the shape, and code for the arithmetic and cross-field rules it can't express.
Enforce Semantic Rules: Whitelists, Cross-Field Logic, and Safety
Semantic validation is where "is this a string" becomes "is this a valid value in this context."
Whitelists over blacklists. Every time you try to list "bad" characters or "bad" words, someone finds a variant you missed. Enumerate what's allowed instead. Cross-field consistency. A confirm_password must match password; a state must pair with the correct country; a start_date cannot exceed end_date. These checks belong after individual field checks pass. Safety as data. Reject HTML-like markup, control sequences, and format strings where they don't belong. Beyond simple allowlisting, apply the right output encoding at the sink: parameterized SQL rather than string concatenation, context-aware escaping in HTML, and an argument array for shell execution. Validation is a defense-in-depth layer, not a replacement for correct encoding. A string containing ' is valid in a name and invalid as a SQL identifier; knowing where the value goes decides which check you run. Format strings. Reject %s-style patterns from user input when they'll be interpolated into a format string. In Python, str.format with braces or % formatting with user-controlled format specifiers is a real hazard; pass user data as arguments, never as the format itself.
Handle Nulls, Empty Strings, and Parsing Ambiguity at the Boundary
Many "invalid input" bugs are actually representation bugs. The string "null", the string "", an absent field, and a JSON null are four different things. Pick a contract: treat null as "not provided," empty string as "provided as empty," and reject the literal "null" for fields where it's not a legitimate value.
Parsing ambiguity applies to numbers and booleans too. The string "1" might be true, one, or a version. The string " 12 " trims to "12" but "12.0" parses to a float, not an int. If your API accepts "12.0" for an integer ID, you'll have silent conversions; reject with a clear message or document the acceptance.
At the boundary of untrusted input, also enforce a maximum request size and a maximum number of fields. A string of 1 GB passes every character-level check you write and still takes down the process.
Decide Where Validation Runs and Where Errors Go
Validation should run in two places with clear roles. Client-side validation is a UX nicety: immediate feedback, less wasted traffic. Server-side validation is the authority: it survives malicious clients, curl, and old app versions, and it's the only one that matters for integrity.
Do not duplicate every rule in both; instead, share a schema or adapt a single definition per field. (In this space, JSON Schema, Pydantic models in Python, Zod in TypeScript, and Java Bean Validation are common ways to declare rules once and report errors consistently.)
Error messages deserve design. A good message names the field, says what was expected, and avoids echoing raw user content back into logs or pages. "Weekday field must be one of Mon–Fri" beats "Invalid input" and beats "Field 'day' had value