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:
- Allowlist, not blocklist: write down what's allowed (a number from 13 to 120), instead of guessing everything that isn't. Strange input nobody thought of is refused automatically, because it's not on the list of what's allowed.
- Refuse, don't fix: if the age is
"twenty", return an error. Don't guess what was meant. - Validate as early as possible: check at the door, as soon as the request reaches the server, before the data touches the database, a file or a query.
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 }
}
typeof data.name !== 'string'catches a field that's missing (undefined) or of the wrong type. Only after that is.lengthsafe to read:.lengthofundefinedcauses an error.data.name.length > 50is the upper limit. A lower limit alone isn't enough: a 56 character name must be refused too.Number.isInteger(data.age)isfalseforundefined, the text"25",NaNand25.5. So an age that wasn't sent at all is refused as well.{ valid: errors.length === 0, errors }: with no errors, the result is exactly{ valid: true, 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)
})
z.number().int().min(13).max(120)reads from the left: a number, whole, at least 13, at most 120. If the rule is only "not negative", writez.number().min(0).max(120)..nonnegative()means the same as.min(0), while.positive()means more than 0.safeParsedoesn't throw an error. It always returns an object:{ success: true, data }when the data passes, or{ success: false, error }when it fails.- 422 Unprocessable Content is the status for "the request is well formed, but what's in it fails the rules".
z.flattenError(result.error).fieldErrorsgroups the error messages per field for that response.
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'],
];
}
}
- A Form Request is a Laravel class that holds validation rules. A controller that uses it only runs when every rule passes. When one fails, Laravel automatically answers
422with an error message per field. - Rules can be written as an array, or as one string split by
|, like theemailline. - The
emailrule checks the email's format.email:rfc,dnsis stricter: it also checks that the email's domain has an MX record (the DNS record that names the domain's mail server).
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.
- Client validation (in the browser) gives quick feedback before the request is sent. That's about UX (how easy the app is to use).
- Server validation is the only one that really holds wrong data back. That's about security, and it's required.
- So do both. With Zod, the same schema can be used on both sides.
What people forget to validate
- Body size: in Express,
app.use(express.json({ limit: '1mb' }))refuses a request body bigger than 1 MB before reading it. - Text length and array size: for example
'items' => ['required', 'array', 'max:50']in Laravel, orz.array(...).max(50)in Zod. - URL parameters: ids, slugs (the page name in a URL) and page numbers are outside input too.
⚠️ Bad data that still gets past validation
- Validating only in the frontend.
curlskips it in one line. The server must always check again. - Only a lower limit.
name.length < 2without> 50lets a 56 character name through. - Treating a missing field as passing.
if (data.age && data.age < 13)skips an age that wasn't sent. The reason:undefinedmakes thatifconditionfalse, so no error is added. Check the type first, for example withNumber.isInteger. - Numbers from a form are still text. An
<input>value is always a string, so"25"failsz.number(). Convert it first withNumber(...), or usez.coerce.number(), which turns the value into a number before checking it.
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.