CCyberwiki

Input validation

Before an application uses the data it receives, input validation checks that the data meets the application's requirements.1 The check covers raw data, such as strings, numbers, parameters and file contents, and metadata about that data, such as headers and declared sizes.2 Without it, or with a faulty one, code goes on to use input that may lack "the properties that are required to process the data safely and correctly".2

Validation lowers the risk of malformed data, invalid business operations and excessive resource use. It does not replace the defences that apply when the data is used: parameterized queries against SQL injection, Output encoding against Cross-site scripting, and a separate Authorization check, since a well-formed account number does not mean the caller may open that account.1

Syntax and meaning

A validator checks two things. Syntax is the type and format of a value. Semantics is whether the value makes sense for the operation: a booking needs two valid dates, and the end date must come after the start date.1 The word "boat" passes a check for letters and digits and is still wrong in a field that expects a colour such as "red" or "blue".2

Table 1. Rules per kind of field, after the OWASP Input Validation Cheat Sheet
FieldRules
Fixed choicesExact membership in the allowed set, including values from drop-down menus
Numbers and datesType, format, minimum and maximum
StringsLength limits and the characters or structure the field needs
ObjectsWhich fields are allowed, which are required, and how missing or null values are handled
ArraysMinimum and maximum number of items, and a check of every item, including nested objects

Turning text into an integer proves the type only. A quantity of 900,000 is a valid integer and may still be an unacceptable order.1

Allowlists and denylists

An allowlist defines what is accepted and rejects everything else. A denylist tries to name every harmful input and "is likely to miss at least one undesirable input", the more so when the surrounding code changes.2 Denylists also block legitimate data: rejecting apostrophes turns away names such as O'Brien and still leaves a joined SQL query open to injection.1

CWE uses the term in a narrow sense: checking whether input already conforms, without changing it. Filtering, which removes characters, and escaping, which prepares a value for the place it is inserted, are separate techniques with their own entries (CWE-790 and CWE-116).2 Stripping characters to "clean" an input is a poor way to make it safe, because the removal can change what the value means.1

Where validation runs

Checks in the browser, such as the HTML attributes required and type="email", give users quick feedback.3 They provide no security, because a user can change the request after the browser has checked it or send the request with another program.4 Every rule therefore runs again on the server.2 In Next.js, an exported Server Action can be called with a direct POST request, without the form that normally calls it.5

Data from inside a system also crosses trust boundaries: internal APIs, partner feeds, queues and stored records are validated by the component that receives them.1 When data from several sources is combined, the combined result is checked, since parts that pass alone can break a rule together.2

Order of checks

A size limit on the request applies before the body is read and parsed, and the parser itself has limits such as maximum nesting depth. A schema check that runs after parsing cannot help a parser that has already run out of memory.1 Encoded input is decoded once, following the protocol, and the check runs on that decoded form; decoding it again later can undo the check.1

A regular expression used as a validator matches the whole value, with an API such as Python's fullmatch. The input length is limited before matching, patterns with heavy backtracking are avoided, and a timeout counts as a failed check.1

Schema validation in code

Schema libraries state the rules for a whole request in one place. The Next.js documentation shows Zod or Valibot for server-side checks of form data.3 In Zod, .safeParse() returns an object that holds either the checked data or a ZodError; .parse() throws the error instead.6 A plain z.object() drops keys it does not list, and z.strictObject() rejects them.7

// app/api/orders/route.ts (Next.js route handler)
import { z } from 'zod'

const Order = z.strictObject({
  size: z.enum(['S', 'M', 'L']),
  quantity: z.int().min(1).max(20),
  note: z.string().max(500),
})

export async function POST(request: Request) {
  const result = Order.safeParse(await request.json())
  if (!result.success) {
    return Response.json({ error: 'Invalid order' }, { status: 400 })
  }
  // result.data holds only the three checked fields
}

A body that adds "price": 0 is rejected, which also blocks the extra fields used in mass assignment. The request is refused as a whole; the code never continues with partly checked data.1 Zod's .safeParse() reports every issue, so a million invalid array items produce a million issues; a .max() on the array or a body size limit bounds that work.6

In Python, Pydantic raises ValidationError when data cannot be turned into a model. It ignores unknown fields by default and rejects them when extra is set to 'forbid'.8

Some inputs need more than a validator. User-written HTML goes through a maintained HTML sanitization library. For uploads, the file name and declared content type are data from the client, and an allowed extension says nothing about the file's contents. A well-formed email address does not prove that the sender can read that mailbox.1 A file name used to build a path can lead to Path traversal.

Classification and testing

CWE-20, Improper Input Validation, ranks 18th in the 2025 CWE Top 25, down from 12th the year before, with two CVEs in the Known Exploited Vulnerabilities catalog catalogue.9 MITRE marks it as discouraged for mapping real vulnerabilities: it is often used in reports that lack detail, it is not useful for trend analysis, and more specific children exist, such as CWE-1284 (specified quantity) or CWE-1287 (specified type).2 The OWASP Top 10 places CWE-20 under A05:2025 Injection.2

Static application security testing tools find some missing checks but can miss custom validation code and report false positives; business rules need a person to review them. Fuzzing sends unexpected input: the application should answer with its own error message, and a crash or an interpreter error shows that the input was not handled.2

In SecFlash

SecFlash reports SF-SEC-681 on the Security page when an API endpoint, tested with requests built from its API description, crashes or accepts input it should refuse. In source code, SF-SEC-740 marks a record that takes every field a request sends, and SF-SEC-794 marks uploads saved without a check of their type; both show on the Security page.

See also

References

  1. a b c d e f g h i j k l "Input Validation Cheat Sheet". OWASP Cheat Sheet Series. OWASP Foundation.
  2. a b c d e f g h i j "CWE-20: Improper Input Validation". Common Weakness Enumeration. MITRE.
  3. a b "Forms". Next.js documentation. Vercel.
  4. back MDN contributors. "Client-side form validation". MDN Web Docs. Mozilla.
  5. back "Data security". Next.js documentation. Vercel.
  6. a b "Basic usage". Zod documentation.
  7. back "Defining schemas". Zod documentation.
  8. back "Models". Pydantic documentation.
  9. back "2025 CWE Top 25 Most Dangerous Software Weaknesses". Common Weakness Enumeration. MITRE.