Input Validation & Schema — Security

Input validation: check every piece of data from outside against clear rules before it's used. Write allowlist rules (what's allowed), refuse wrong data…

Your sign-up form already refuses an age under 13: a red message appears, and the Sign up button can't be clicked. But the form is only one way in. Someone can send {"age": 10} straight to the API with curl (a program for sending requests from the terminal), without ever opening the page.

That's the job of input validation: every piece of data from outside is checked against clear rules, before it's used. Picture a bank teller taking a deposit slip. The name must be filled in, the account number must be 10 digits, and the amount must be a positive number. A wrong slip is handed back with a note on the wrong box, not quietly fixed. Even though the bank's app on your phone already checked that slip, the teller checks it again, because people can walk in with a slip they made themselves. In your app, the teller is the server, the slip is the data in the request, and the phone app is the form in the browser. A slip made at home is a request sent with curl.

Rules for each field

In the Lab and in the exercise, the sign-up form has three fields (input boxes). These are the rules:

Field Rule
name required, text, 2 to 50 characters
email required, text, contains @ and .
age required, a whole number, 13 to 120

There are three principles behind these rules:

Manual validation in JavaScript

The function validateInput below checks the three rules in the table. Each rule that fails adds one message to the errors array:

function validateInput(data) {
  const errors = []

  if (typeof data.name !== 'string' || data.name.length < 2 || data.name.length > 50) {
    errors.push('name must be 2 to 50 characters')
  }
  if (typeof data.email !== 'string' || !data.email.includes('@') || !data.email.includes('.')) {
    errors.push('email must contain @ and .')
  }
  if (!Number.isInteger(data.age) || data.age < 13 || data.age > 120) {
    errors.push('age must be a whole number from 13 to 120')
  }

  return { valid: errors.length === 0, errors }
}

These are the function's results for the data the Lab uses too:

Input Result
{ name: 'Budi', email: '[email protected]', age: 25 } { valid: true, errors: [] }
{ name: '', email: 'invalid', age: 10 } valid: false, 3 errors: name, email, age
{ name: 'A', email: '[email protected]', age: 25 } valid: false, name too short
{ name: 'Budi', email: '[email protected]' } valid: false, age missing

A schema with Zod

Writing an if for every rule quickly gets long. A schema is a list of rules for the shape of the data, written once and then used to check data. Zod is a popular schema library for JavaScript and TypeScript. In this example, the schema is used in an Express handler for POST /api/users:

import { z } from 'zod'

const UserSchema = z.object({
  name: z.string().min(2).max(50),
  email: z.email(),
  age: z.number().int().min(13).max(120),
})

app.post('/api/users', (req, res) => {
  const result = UserSchema.safeParse(req.body)
  if (!result.success) {
    return res.status(422).json({ errors: z.flattenError(result.error).fieldErrors })
  }
  db.users.insert(result.data)
  res.status(201).json(result.data)
})

For { name: '', email: 'invalid', age: 10 }, the server answers with these messages from Zod 4, exactly as the Lab shows them:

{
  "errors": {
    "name": ["Too small: expected string to have >=2 characters"],
    "email": ["Invalid email address"],
    "age": ["Too small: expected number to be >=13"]
  }
}

In Laravel

In Laravel, the same rules go in a Form Request:

class StoreUserRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'min:2', 'max:50'],
            'email' => 'required|email|max:255',
            'age' => ['required', 'integer', 'min:13', 'max:120'],
        ];
    }
}

The client is for UX, the server is for security

Validation in the browser can be skipped: with DevTools, curl, Postman (an app for trying APIs), or a proxy like Burp Suite (a tool for holding and changing requests). So if the server doesn't validate, {"age": 10} sent with curl is still accepted, and that wrong data lands in the database.

What people forget to validate

⚠️ Bad data that still gets past validation

TL;DR: Input validation: check every piece of data from outside against clear rules before it's used. Write allowlist rules (what's allowed), refuse wrong data without fixing it, and check as early as possible. A manual function collects error messages in an array and returns { valid: errors.length === 0, errors }. The rules: a name of 2 to 50 characters, an email containing @ and ., an age that's a whole number from 13 to 120, and a missing field refused too. In a Zod schema (a list of rules written once), the age rule is z.number().int().min(13).max(120), or .min(0) for "not negative". Zod's safeParse gives errors per field, and the server answers 422. In Laravel, the rules go in a Form Request, with rules like required|email|max:255. Client validation (in the browser) is for UX (how easy the app is to use), server validation is for security. Do both, because client validation can be skipped, for example with curl (a program that sends requests).

⚡ Check at the door

Meaning: Input validation: every piece of data from outside is checked against clear rules before it's used. Write down what's allowed (an allowlist), refuse what's wrong without guessing what was meant, and check as early as possible, as soon as the request reaches the server.

⚡ Manual validation

Write:

if (!Number.isInteger(data.age) || data.age < 13 || data.age > 120) {
  errors.push('age must be a whole number from 13 to 120')
}
return { valid: errors.length === 0, errors }

Meaning: This code checks data.age, the age in the sign-up data. A wrong age adds one message to errors, so valid becomes false. Number.isInteger is false for undefined, the text "25", and 25.5, so an age that wasn't sent is refused too. An upper limit is required as well, not just a lower one.

⚡ A schema with Zod

Write:

age: z.number().int().min(13).max(120),

Meaning: Zod is a schema library: the rules are written once, then used to check data. This line means age must be a number, whole, at least 13 and at most 120. safeParse checks data without throwing an error, and on failure the server answers 422. In Laravel, a Form Request (a class that holds validation rules) does the same.

⚡ The client is for UX, the server is for security

Guess first: the form already refuses an age under 13. If the server doesn't validate, is {"age": 10} sent with curl (a program that sends requests) accepted?

Accepted, and that wrong data lands in the database. curl sends the request straight to the server without opening the form, so the validation in the browser is skipped.

Meaning: Client validation (in the browser) is for UX (how easy the app is to use), server validation is for security. Do both. Server validation is the required one.

What you will learn