Input Validation: A Practical Guide
Validate at the boundary, allowlist what is expected, and never trust the client. A practical guide to validating input safely.
By Velloreth
What validation is for
Input validation checks that the data an application receives matches what it expects. It confirms the type, the format, the length and the range, and it rejects anything that does not fit.
The purpose is twofold. It protects the application from malformed data that would cause a crash or a corrupt record, and it reduces the attack surface by refusing input that a downstream component might mishandle.
Validation is not a substitute for encoding. A value can be perfectly valid and still be dangerous in the wrong context. A name that is a valid string is still a problem if it is rendered as HTML without encoding. Validation and encoding are separate layers.
Validate on the server
Client-side validation is for usability. It gives the user immediate feedback without a round trip, and it is worth having. It is not a security control, because an attacker can send a request directly to the API with any payload.
The server is the only place an attacker cannot bypass. Every input that reaches the server must be validated there, regardless of what the client checked. A form that validates in the browser and trusts the result on the server is a form with no validation at all.
Share the rules where you can. A schema defined once and used on both sides keeps the two consistent, and it avoids the case where the client accepts a value the server rejects.
Allowlist, not blocklist
An allowlist defines what is permitted. A field that must be a two-letter country code accepts exactly the codes in the list and rejects everything else. A new attack technique is rejected by default, because it is not in the list.
A blocklist defines what is forbidden. A field that rejects a script tag accepts everything else, including an image tag with an error handler, an SVG with a load handler, and an encoding that the filter does not recognise. A blocklist must be updated for every new technique, and it fails open.
The rule: allowlist where the set of valid values is known, and use a strict format check where it is not. A blocklist is a last resort.
Validating by type
A string needs a length bound, and often a character set. An unbounded string is a denial-of-service vector, because a very large value consumes memory and storage.
const name = z.string().min(1).max(100);
A number needs a range and an integer check where appropriate. A number that is used as an index or a limit must be bounded, or it becomes a resource exhaustion vector.
const page = z.coerce.number().int().min(1).max(1000);
An email should be checked for a plausible shape rather than a perfect one. The only reliable verification is a confirmation message, so a strict regular expression rejects valid addresses without adding security.
const email = z.string().email().max(254);
A URL must have its scheme checked. A URL that is fetched by the server is a server-side request forgery vector if it can point at an internal address.
const url = z.string().url().refine((u) => {
const parsed = new URL(u);
return ['http:', 'https:'].includes(parsed.protocol);
});
An enum is the strongest check, because the value must be one of a fixed set. A status, a role, or a sort direction should always be an enum.
const sort = z.enum(['name', 'created', 'price']);
A file upload needs a size limit, a content-type check, and a check of the actual content rather than the declared type. A file that is stored and served must not be executable, and its name must not be used as a path.
A schema at the boundary
The pattern that keeps validation consistent is a schema that every request is parsed through, at the edge of the application.
import { z } from 'zod';
const CreateUser = z.object({
email: z.string().email().max(254),
name: z.string().min(1).max(100),
age: z.number().int().min(13).max(120).optional(),
});
app.post('/users', (req, res) => {
const parsed = CreateUser.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({
error: 'validation_failed',
fields: parsed.error.issues.map((i) => ({
field: i.path.join('.'),
message: i.message,
})),
});
}
// parsed.data is now trusted
createUser(parsed.data);
});
Parse once, then trust. After the boundary, the value has a known shape, and the rest of the application does not need to re-check it. This is the difference between validation as a layer and validation scattered through the code.
Reject unknown fields. A schema that strips or rejects extra fields prevents mass assignment, where an attacker adds a field such as isAdmin to a request body.
Validation and the rest of the layers
Validation is one layer in a set, and it is worth being clear about what it does and does not do. It confirms that a value has the expected shape, which prevents a malformed value from reaching a component that would mishandle it. It does not make a value safe for every context, because a valid string is still dangerous if it is rendered as HTML or concatenated into a query. The layers that follow are output encoding for the rendering context, parameterised queries for the database, and a content security policy for the browser. A value that passes validation and is then encoded for its context is safe; a value that passes validation and is then concatenated is not. The practical consequence is that validation reduces the attack surface but does not close it, and a team that treats it as the only defence has a false sense of security.
Common mistakes
Validating only on the client. The server must validate, because the client can be bypassed.
Using a blocklist. A blocklist fails open and must be updated for every new technique. A filter that rejects a script tag still accepts an image tag with an error handler, and a dozen other vectors.
Validating the type but not the length. An unbounded string is a denial-of-service vector.
Trusting the declared content type of an upload. The declared type is attacker-controlled; check the actual content.
Using the file name as a path. A name such as ../../etc/passwd escapes the upload directory. Generate a name and store the original as metadata.
Returning the internal error. A stack trace or a database error leaks the implementation. Return a field-level message and a code.
Validating in the controller and again in the model with different rules. Two sources of truth diverge. Define the schema once.
A quotable summary
Input validation checks that data matches the expected type, format, length and range, and it must happen on the server because the client can be bypassed. An allowlist is safer than a blocklist because it fails closed. A schema parsed at the boundary lets the rest of the application trust the value, and it should reject unknown fields to prevent mass assignment. Validation is not encoding: a valid value can still be dangerous in the wrong context, so the two layers are both required.
Related reading
For the output side, see xss-prevention-guide and for the query side, sql-injection-prevention. For the broader context, form-validation-patterns and api-error-responses-guide.