Validate API Parameters and Define Data Formats

Convert untrusted input into clearly defined data that business logic can use

🎯 Introduction

By the end of this article, you will be able to define validation rules, reject invalid input, and use validated data.

🧾 Define field rules first

For a user profile endpoint, require:

FieldRuleValid example
nameString, 1–40 units long after trimming surrounding whitespaceMing
ageInteger from 0 to 15020
Other fieldsReject them to prevent submission of internal fields such as roleOmit

Valid JSON guarantees only correct syntax, not compliance with these rules. Use Zod, a validation library for checking data types and content, to describe them.

Install the dependency for this section:

npm install zod@4.6.7

🏷 Define the name rule

Create user-schema.mjs:

user-schema.mjs
import { z } from 'zod';

const nameSchema = z.string().trim().min(1).max(40);

This requires a string, trims surrounding whitespace, then checks its length. Empty or whitespace-only strings fail. Length uses JavaScript string counting, so some emoji occupy multiple units.


🔢 Define the age rule

Add the age rule in the same file:

user-schema.mjs
const ageSchema = z.number().int().min(0).max(150);

The JSON number 20 passes; the string "20" does not. This example does not coerce types, so incorrectly formatted client data is not silently accepted.


🧩 Combine the rules into a user profile schema

Continue by exporting the complete schema:

user-schema.mjs
export const userSchema = z.strictObject({
    name: nameSchema,
    age: ageSchema
});

strictObject allows only declared fields. Missing name or age, or an extra role field, causes failure. After successful validation, use the returned data, whose name has already been trimmed.


🚪 Validate in the endpoint

Create validation-server.mjs:

validation-server.mjs
import express from 'express';
import { userSchema } from './user-schema.mjs';

const app = express();
app.use(express.json({ limit: '16kb' }));

Add a profile validation endpoint:

validation-server.mjs
app.post('/users/validate', (req, res) => {
    const result = userSchema.safeParse(req.body);
    if (!result.success) {
        const message = result.error.issues[0].message;
        return res.status(400).json({ error: { code: 'INVALID_INPUT', message } });
    }
    res.json({ data: result.data });
});

safeParse returns a validation result, so ordinary validation failures need no custom exception class. On failure, issues contains the errors; this example returns the first message. On success, data is the validated object. The endpoint only validates and echoes data; it does not write to a database.

Finally, start listening:

validation-server.mjs
app.listen(3000, '127.0.0.1');

🧪 Check the rules against inputs and results

Run node validation-server.mjs, then submit:

curl -i http://127.0.0.1:3000/users/validate -H 'Content-Type: application/json' -d '{"name":" Ming ","age":20}'

Expect 200 and {"data":{"name":"Ming","age":20}}. Changing age to a string, removing name, or adding role all produce 400 with INVALID_INPUT.

Error codes exposed to the frontend should remain stable. Message text can be translated or adjusted for the product. Do not expose internal errors, such as database exceptions, as field validation messages.


❓ Questions and Answers

Q1: Is backend validation necessary if the frontend already validates?

Yes. Requests can bypass the page, so the backend must check the values it actually receives.

Q2: Can I keep using req.body after validation succeeds?

Use result.data, which contains values processed by the rules, such as the trimmed name.

Q3: Does valid field formatting authorize an update?

You must also check identity, permissions, and business rules, such as whether a name is already taken.


🧪 Practice

Add an optional biography field that accepts a string with a maximum length. Compare the results for an omitted field and an overly long value.

// Write your code here