Skip to content

Input validation

Introduction

Check the format, range, and length of all external input (parameters, request bodies, files) first, and reject whatever does not pass.

Why use it

  • Security: almost every attack (SQL injection, XSS, and more—see Common attacks) starts with unchecked input.
  • Stability: age sent as "abc" or a name that is 10 MB of text will blow up deep in the stack if you do not stop it.
  • Better UX: telling the caller early which field failed and why is far friendlier than a 500.

How to do it

  1. Never trust the client: frontend checks are UX only; the backend must validate again because requests can bypass the UI.
  2. Allowlist thinking: define what is allowed, do not try to list everything that is forbidden.
  3. Check four things: type, required, length/range, and format (email, phone, enums).
  4. Separate validation from business rules: format problems (bad email) stop at the gate; business problems (out of stock) belong in the business layer.
  5. Failures must be clear: return 400 or 422 and name the field; see Error handling for the format.
  6. Cap overall size: request body, upload size, and list length all need upper bounds.

Component comparison

FluentValidation

Self-hosted open sourceOpen sourceOpsLow

A C# library that puts validation rules in a dedicated class, with rules that read like sentences (name must not be empty, at most 50 characters), kept separate from the data model.

Best forC# projects with many rules or cross-field checks.

Avoid whenYou only have a few simple "required, length" rules and the built-in attributes are enough.

Pros

Rules live in one validator class, so complex rules (cross-field dependencies, conditional checks) stay readable

Validator classes can be unit-tested on their own

Error messages are customizable and easy to return to the frontend

Cons

Requires an extra validator class, which feels verbose for simple endpoints

You must call it from the endpoint yourself, or install an integration package to hook it into the framework

The team has to learn one more way of writing validation

Official docs ↗

DataAnnotations (attributes)

Built into the frameworkOpsLow

Attach tags directly to fields of a C# data class, such as [Required] and [StringLength], and the framework checks them automatically.

Best forC# projects with simple rules that use MVC controllers.

Avoid whenValidation rules are complex, or the same data class needs different rules in different scenarios.

Pros

It ships with .NET, so you do not install another validation package

Rules sit next to the fields and are visible when you open the class

MVC controllers include them in validation automatically

Cons

Complex rules are weakly expressed and often need a custom attribute

Rules are bound to the data class, so reuse in another scenario is awkward

Whether Minimal APIs validate automatically depends on the version

Pydantic

Self-hosted open sourceOpen sourceOpsLow

Declare field requirements with typed data classes in Python; incoming data is automatically checked and type-converted. FastAPI is built on it.

Best forProjects using FastAPI (or another Python API service).

Avoid whenThe project uses Django, whose forms and serializers already include validation.

Pros

Type annotations are the rules, so very little code

In FastAPI, a failed validation automatically returns 422 and points to the offending field

Also generates field descriptions in the API docs automatically

Cons

Some types such as EmailStr require an extra dependency package

Pydantic v1 and v2 differ in syntax, so older projects need code changes to upgrade

Business rules that need database lookups still have to be written by hand

Official docs ↗

DRF serializers / Django forms

Built into the frameworkOpsLow

Django's built-in validation: APIs declare field rules with Django REST Framework serializers, regular pages use Django forms, and incoming data is checked automatically.

Best forProjects that build APIs or admin backends with Django (including DRF).

Avoid whenThe project is not Django, or it uses FastAPI (use Pydantic).

Pros

Works closely with Django models, so field rules on the model can be reused directly

Failed validation automatically returns error messages with field names

The same class handles serialization (output) and validation (input), so less code

Cons

Only applicable to Django projects

Rules live in the serializer class, and complex cross-field rules need a hand-written validate method

Business rules that need database lookups still have to be written by hand

Official docs ↗

Hand-written if checks

Hand-rolledOpen sourceOpsLow

Write ifs at the endpoint entry yourself, check each field one by one, and return an error when something is invalid.

Best forTiny scripts or prototypes with only one or two endpoints.

Avoid whenThere are many endpoints or multiple collaborators.

Pros

No library, and the logic at the entry point is obvious

Even an unusual rule can be written directly with an if

During a prototype you can change rules without learning a library first

Cons

Every endpoint repeats the checks, and a missed field becomes a hole

Error formats drift apart and fail to line up with the shared format

Once there are many rules, the code gets long and hard to maintain

zod

Open-source libraryOpen sourceOpsLow

A TypeScript-first schema validation library: one definition gives you both runtime validation and static types.

Best forValidating requests, environment variables, and third-party responses in any TypeScript backend.

Avoid whenThe team has standardized on class-validator (the NestJS default) and does not want a second system.

Pros

Validation and type inference share one source, so you never get "correct types but wrong data"

Broad ecosystem integration (Fastify, Hono, tRPC, form libraries)

Structured error messages that are easy to turn into a uniform error response

Cons

Compile-time and runtime overhead can be significant for very large schemas

Different in style from NestJS class-validator; picking just one is clearer

Major version upgrades may include breaking changes

Official docs ↗

validator

Open-source libraryOpen sourceOpsLow

Declares validation rules on struct fields, and rejects bad data at the Axum or Actix extractor before it reaches business code.

Best forValidating request bodies and parameters in any Rust API.

Avoid whenRules are highly dynamic and need to be configurable (consider a rules engine).

Pros

Declarative, so the request struct is self-explanatory

Sits next to serde deserialization, so types and checks live together

Custom validation functions are supported

Cons

Complex cross-field rules need a custom function

Error messages must be turned into your uniform error response

A wrong attribute is only caught at runtime

Official docs ↗

go-playground/validator

Open-source libraryOpen sourceOpsLow

The most widely used struct validation library in Go, declaring rules with struct tags.

Best forFormat and range validation of request structs.

Avoid whenMost rules are business semantics (those belong in the business layer).

Pros

Declarative tags, already integrated with frameworks such as Gin

Rich rule set with cross-field and custom validation

Widely used in the community

Cons

Rules live in string tags, so typos are not caught at compile time

Error messages must be localized and structured by you

Complex business rules still belong in the business layer

Official docs ↗

Checklist

  • All external input is validated on the backend; do not rely on the frontend
  • Strings have length caps, numbers have ranges, enums use an allowlist
  • Request bodies and uploads have size caps
  • Validation failures return 400/422 and name the field
  • Database queries use parameters, not string concatenation