To check whether an entered variable is invalid, compare it against an explicit set of rules the moment it arrives: confirm it exists, confirm its type, then check format, range, and business rules in that order, and reject it with a clear message if any rule fails. The key condition is that "invalid" is never a property of the raw value alone. A string like "42" is valid if you asked for a quantity and invalid if you asked for a US ZIP code; a blank field may be acceptable for an optional nickname and fatal for a login name. Validation only makes sense against a declared expectation for that specific input.
That framing matters because most validation bugs come from skipping the expectation and testing the value directly. Someone checks if not value, which catches empty strings and None but silently treats 0 and False as missing. Someone else reaches for a truthiness test on a string that might contain "0", the one non-empty string that is falsy in some dynamic languages' loose comparisons. The fix is to write the rule down first, then implement the check in a fixed sequence so the earliest, cheapest failure stops the pipeline.
Decide what "invalid" means before you write the check
Every input has a contract. Write it as four separate clauses, because each clause catches a different class of mistake and each one needs a different error message.
Presence. Is the variable allowed to be missing? A required enrollment date cannot be absent, but a middle name can. Distinguish "missing" (the key was never sent) from "empty" (the key was sent with a blank value) if your system treats those differently, because downstream code often does.
Type. Is the value the kind of thing the rule expects? A count must be an integer, not a decimal string. A price must be a number with at most two decimal places. A date must be a parseable calendar date, not the literal text "next Tuesday."
Format and shape. Does the value match the required pattern? An email needs an @ with text on both sides, a postal code needs the right length for its country, and an identifier might need a fixed prefix.
Range and domain. Is the value inside the allowed set? Ages between 0 and 130, quantities of at least 1, country codes drawn from an enumerated list, start dates no later than end dates.
Write these down as a short specification, ideally next to the code that enforces them. A one-line contract per field prevents the classic drift where the front-end allows something the database rejects six months later. It also tells you what success looks like: a valid value passes all applicable clauses; anything else is invalid and should be rejected at the boundary rather than repaired deep in your logic.
Validate in a fixed order: presence, type, format, range, rules
The order is not arbitrary. Cheap, unambiguous checks go first so you never waste work parsing a value that was never there, and so error messages point at the real problem instead of a symptom.
1: Check presence. If the variable is absent or null and the field is required, stop and report "required." In languages where None/null and an empty string are distinct, test explicitly rather than relying on truthiness, so 0 and False survive as legitimate values. 2: Check type. If you received raw text from a form or query string, coerce it deliberately and catch the failure. In Python, int("12.5") raises; in JavaScript, Number("12.5") returns a float you may not want for a count. Reject values whose type conversion fails rather than defaulting them to zero. 3: Check format. Apply the pattern or parse rule for that field. For dates, parse with an explicit format and verify the result round-trips to the same value, which catches impossible dates like February 30 that some parsers silently roll forward. 4: Check range and domain. Compare the parsed value against numeric bounds, string length bounds, or an allowed enumeration. This is where you catch quantity = 0 when the minimum is 1, or a percentage of 140. 5: Check cross-field and business rules. Start date before end date, password matches confirmation, discount code applies to the selected product. These run last because they need multiple values.
Expected result: the first failing clause returns a specific rejection, and a value that passes all clauses is safe to use. A simple success check is to feed known-good and known-bad samples through the same function and confirm each lands on the correct side. Build a tiny table of cases, including boundary values, and rerun it whenever the rules change.
Watch the classic traps: blank strings, zero, whitespace, and coercion
Most "invalid input" incidents trace back to four specific confusions. Naming them makes them easier to test for.
Empty versus falsy. if not value: rejects 0, 0.0, False, and empty collections along with blank strings. When the field is a count or a flag, that is wrong. Test value is None or value == "" explicitly, and let zero through if zero is legal.
Whitespace-only input. A field containing three spaces is not empty by character count but is empty to a human. Trim before the presence check if leading and trailing spaces carry no meaning, but do not trim silently inside a field where spacing is part of the format, such as a formatted account number.
Loose coercion. Remember that in JavaScript, Number("") is 0 and Number(" ") is 0, so a blank numeric field can quietly become a valid zero. In Python, bool("False") is True because it is a non-empty string. Convert first, check the conversion result, then validate the converted value.
Locale and encoding surprises. A comma decimal separator, a non-breaking space pasted from a document, or a full-width digit will fail a naive numeric check. Decide whether those are invalid (reject with a helpful message) or normalized (strip and convert), and document the choice.
A concrete example: a bug report says "customers can place orders for zero items." The code did quantity = int(request.get("quantity", 0)) and then if not quantity: raise. But the default was already 0, so a missing field looked like a legitimate zero after conversion, and the check never fired because the presence test used a default that masked absence. The fix was to read the raw value, test for missing explicitly, then convert and enforce 1 <= quantity <= 999.
Use the right tool: built-in checks, regex, parsers, and schemas
Match the mechanism to the nature of the rule. Regex is good at shape, weak at meaning; parsers are the reverse.
Language built-ins (isinstance in Python, Number.isInteger in JavaScript, Integer.tryParse in C#) handle type questions cleanly. Prefer them to hand-rolled type checks. Regular expressions are efficient for fixed-shape formats: a six-digit code, a YYYY-MM-DD string, a hex color. Keep them anchored with ^ and $ so a substring match does not sneak through, and test them against both valid and invalid samples because a subtly wrong pattern can pass almost everything. Dedicated parsers beat regex for dates, URLs, email addresses, and currency. Parse into a structured object, then validate the object. For dates, prefer an explicit format string over a permissive parser, which may accept "01/02/2026" as either January 2 or February 1 depending on locale. Schema validators (JSON Schema, Pydantic, Zod, Joi, and similar libraries) let you declare the whole contract for an object and validate it in one pass. They produce structured errors and scale well when a payload has twenty fields. They are a convenience layer over the same presence-type-format-range sequence, not a replacement for thinking about the rules. Database constraints (NOT NULL, CHECK, foreign keys) are a backstop, not the primary check. Good validation at the boundary gives a friendly message; constraints protect data integrity if a bug slips past.
The trade-off is real. Regex is fast to write and hard to read later; a schema is more setup but self-documenting. For a single field, a plain function with explicit checks is usually clearest. For a whole request body, a schema pays for itself.
Distinguish invalid input from missing, wrong-type, and out-of-range failures
"Invalid" is an umbrella. Splitting it into precise categories improves both the error message and the fix.
Malformed input means the data cannot be interpreted at all: a JSON body that does not parse, an email without an @, a date string that matches no known format. The sender's syntax is wrong.
Wrong type means the value parses but is the wrong kind: you expected an integer and got "abc", or you expected a string and got a number. This often signals a client bug or a schema mismatch, so the message should be technical.
Out of range means the value is well-formed and the right type but outside the allowed set: age 200, quantity -3, a status code not in the enumerated list. The sender's value is implausible or not permitted.
Missing means the field was not supplied when it was required.
Conflicting means two individually valid values break a joint rule, such as an end date before a start date.
Why bother? Because a user who typed letters into a quantity field needs "enter a whole number," while a user who typed 500 into a field capped at 100 needs "quantity cannot exceed 100." One generic "invalid input" message for both is technically true and practically useless.
Reject clearly, log enough, and never crash on bad data
Validation that throws an unhandled exception is not validation; it is a denial-of-service waiting for the right input. Structure the check so failure is a normal, handled outcome.
Return a result object or raise a typed error that carries the field name and rule violated. Respond with a specific, user-safe message and an appropriate status (a 400-class response for malformed or invalid client input in an HTTP API). Do not echo raw input back into HTML without escaping, and do not leak internal details like stack traces or SQL errors that reveal structure.
Log the rejection with the field, the rule, and a redacted value or a note that a value was rejected, depending on whether the data is sensitive. Never log full credit-card numbers, passwords, or personal identifiers. Rate-limit or block clients that send invalid payloads repeatedly if that pattern looks like probing.
For the user-facing side, reject early and list everything wrong at once when the form has several fields, rather than making the person resubmit one error at a time. Preserve the valid entries so a single typo does not wipe the form.
Validate strings by trimming, testing length, and checking content
Strings deserve their own pass because they carry the most hidden assumptions.
Start with an explicit policy on trimming: input.trim() before checking length is common, but do it once and consistently, and decide whether interior whitespace is meaningful. Then check length bounds, not just a maximum. A minimum length of 1 catches blank submissions; a maximum protects against oversized payloads and storage issues. For identifiers, enforce the exact length if it is fixed.
When checking content, distinguish "allowed characters" from "required pattern." A username might allow letters, digits, underscores, and hyphens anywhere, while a US phone number should be normalized to digits first and then checked for a ten-digit length. For free-text notes, do not try to validate grammar; validate length and reject control characters if they cause storage problems.
A worked example: a "company name" field accepts up to 120 characters, trims leading and trailing whitespace, rejects the empty result, rejects strings containing only whitespace, and permits any printable Unicode. A pasted name with a stray non-breaking space at the end would otherwise fail an exact-match lookup later. The check is short, and the rule is written down so the next developer knows why the trim is there.
Validate numbers by converting, then checking type, then bounds
Numbers arrive as text from forms and URLs, so the conversion step is where most problems hide.
Convert with strict rules: reject strings with trailing junk like "12abc" rather than parsing the leading digits and ignoring the rest. Reject empty strings explicitly, since some languages turn them into zero. Reject values with more decimal places than the field allows, or round them deliberately and document the rounding.
After conversion, check the type (Number.isInteger, an integer type in a typed language) and then the bounds. Include both ends: 0 <= age <= 130, 1 <= quantity <= 999, -90 <= latitude <= 90. Test the boundary values exactly, because off-by-one at the limit is the most common range bug.
Two arithmetic clarifications that save grief: a stored price of 19.99 may not compare equal to 20 - 0.01 in binary floating point, so compare with a tolerance or store money in the smallest currency unit as an integer. And when a rule says "increase by 10 percent," that is a 10 percent change; adding ten percentage points to a 20 percent figure gives 30 percent, not 22 percent. Validation messages that quote limits should use the same units as the input to avoid confusing users.
Validate dates, times, and periods against the calendar and each other
Dates combine format and range, with a few sharp edges.
Parse with an explicit format or a strict parser that rejects impossible dates. Some permissive parsers accept "2026-02-30" and silently store March 2, which means a typo becomes a different valid date. Check that the parsed date lies within the allowed window, such as no birth dates in the future and no hire dates before the company existed.
Decide on time zones. A date without a time is a calendar date; a timestamp needs an offset or a declared zone. Comparing a start timestamp and an end timestamp requires both in the same zone or both in UTC. A common failure is "end before start" reported for values that are actually correct in different zones.
For periods, enforce the relationship explicitly: start <= end, and optionally cap the duration, such as "the rental period cannot exceed 90 days." Test the equal-date case to confirm it is allowed or rejected according to the rule you chose.
A quick arithmetic example: if a system stores timestamps in UTC but a user in a negative-offset zone enters 23:30 local time, that is the next day in UTC. Validating "date must be today or later" against local midnight and then storing UTC can produce a record that appears one day earlier to the user. Check the rule against the zone you will actually store.
Validate complex structures with schemas and cross-field rules
As input grows into arrays and nested objects, hand-written checks multiply. A schema declares each field's type, required status, bounds, and format in one place. On access, you validate the whole object and get a list of errors keyed by path, so a nested items.quantity failure is easy to report.
Schemas still need design care. Mark fields optional only when their absence is meaningful, and define defaults explicitly rather than letting the absent value become whatever the language's zero value is. For arrays, check the item count (minimum 1 if at least one entry is required, maximum to bound payload size) and validate every item, not just the first.
Cross-field rules live outside the per-field schema in most validators: password equals confirmation, shipping date after order date, discount applies only to eligible items. Keep them in one place and run them after the per-field checks pass, so messages stay specific.
A worked check: a checkout payload has items (array, at least one), each item with sku (non-empty string, max 40 characters) and qty (integer, 1 to 99). The schema catches a missing items and a string qty; a separate rule sums the quantities and rejects a total over the stock level, which no single field could know. Run the tests against a payload where one item has qty: 0 and confirm the message names that item.
Testing and maintaining validation so it stays correct
Validation drifts when rules change in one place and not another. Treat the rule set as code under test.
Keep a fixture list per field: one valid typical value, the boundary values at each limit, an empty string, a whitespace-only string, a wrong-type value, and a clearly out-of-range value. Assert that each lands on the expected outcome. This suite catches the regression where someone loosens a maximum to fix a complaint and accidentally admits negative values.
Review validation when the contract changes, not just when the bug reports arrive. If the database adds a NOT NULL column, the boundary check must require the field before the database starts rejecting inserts with a stack trace. If a new country joins a service, the postal-code rule needs a new branch.
Finally, separate validation from sanitization. Checking tells you something is wrong; sanitizing tries to fix it. Converting and normalizing (trimming, lowercasing an email, stripping formatting from a phone number) is fine when it is deliberate and tested, but silently "cleaning" user data can turn an invalid value into a plausible wrong one. Reject what you cannot confidently interpret, and say why.
If repeated invalid-input errors on a production system point toward a security incident rather than a user mistake, involve your platform or security team before adding further measures.