What Is Input Validation? The #1 Rule of Web Security

Rule #1 of building anything for the internet: never trust user input. Ever. Not from forms, not from URL parameters, not from API requests. Here's what input validation means, why it matters, and how to make sure AI generates it correctly.

TL;DR

Input validation = checking that user-provided data is safe and expected before your app processes it. Always validate on the server — client-side validation is for UX, not security (it can be bypassed in seconds). Use a validation library like Zod to define what valid data looks like, then reject anything that doesn't match. This single practice prevents SQL injection, XSS, and most common vulnerabilities.

Why "Never Trust User Input" Is Rule #1

Every field a user can type into, every URL parameter, every API request body is an attack surface. Without validation, a user can submit:

  • SQL commands in a name field → SQL injection
  • JavaScript in a comment → Cross-site scripting (XSS)
  • A 500MB string in an email field → denial of service
  • A negative number in a price field → free products
  • An admin role value in a hidden form field → privilege escalation

Input validation is the single most impactful security practice. It stops most attacks at the front door.

Real Scenario: A User Registration API

Your AI Prompt

"Build a user registration endpoint. Validate that: email is a real email format, name is 1-100 characters with no HTML, password is at least 8 characters. Return specific error messages for each field that fails."

What AI Generated (Zod + Express)

// Tested with Zod 3.x + Express 4.x + Node.js 22.x
import { z } from 'zod'

// Define the validation schema — what valid registration data looks like
const registerSchema = z.object({
  email: z
    .string()
    .email('Invalid email address')
    .max(255, 'Email too long')
    .transform(val => val.toLowerCase().trim()),

  name: z
    .string()
    .min(1, 'Name is required')
    .max(100, 'Name must be under 100 characters')
    .regex(/^[a-zA-Z\s'-]+$/, 'Name contains invalid characters'),

  password: z
    .string()
    .min(8, 'Password must be at least 8 characters')
    .max(128, 'Password too long')
})

// The API endpoint
app.post('/api/register', async (req, res) => {
  // Parse and validate — throws if invalid
  const result = registerSchema.safeParse(req.body)

  if (!result.success) {
    // Return specific errors for each field
    return res.status(400).json({
      errors: result.error.issues.map(issue => ({
        field: issue.path.join('.'),
        message: issue.message
      }))
    })
  }

  // result.data is validated AND transformed (email lowered/trimmed)
  const { email, name, password } = result.data

  // Now safe to use — hash password, save to DB, etc.
  const hashedPassword = await bcrypt.hash(password, 12)
  // ...
})

Client-Side vs. Server-Side Validation

Client-Side (Browser)Server-Side (API)
PurposeUser experience — instant feedbackSecurity — the real protection
Can be bypassed?Yes — trivially (disable JS, use curl)No — attacker can't skip it
TechnologiesHTML required/pattern, JavaScriptZod, Joi, express-validator
When it runsBefore form submissionWhen request arrives at server
Required?Nice to haveNon-negotiable

The rule: Client-side validation is a UX feature. Server-side validation is a security feature. Always do both, but never rely on client-side alone.

How Easy Is It to Bypass Client-Side Validation?

# This bypasses ALL client-side validation:
curl -X POST https://yourapp.com/api/register \
  -H "Content-Type: application/json" \
  -d '{"email": "not-an-email", "name": "<script>alert(1)</script>", "password": "x"}'

# No browser involved. No JavaScript ran. No HTML 'required' checked.
# If your server doesn't validate, this malicious data goes straight to your database.

Validation vs. Sanitization

Validation: "Does this data match what I expect?" Reject if no.

Sanitization: "Clean this data so it's safe to use." Transform it.

// VALIDATION: reject bad data
if (!email.includes('@')) throw new Error('Invalid email')
if (name.length > 100) throw new Error('Name too long')

// SANITIZATION: clean data that passed validation
const cleanName = name.trim()                    // Remove extra whitespace
const cleanEmail = email.toLowerCase().trim()    // Normalize
const safeHtml = DOMPurify.sanitize(userContent) // Strip dangerous HTML

// Best practice: validate first, then sanitize what passes

What AI Gets Wrong

1. Client-Side Only Validation

// AI generates this for a form:
<input type="email" required minlength="5">

// This is UX — NOT security. The server must also validate.
// Ask AI: "Add server-side validation for this endpoint using Zod"

2. No Length Limits

// AI validates format but not size:
const schema = z.object({
  bio: z.string()  // No max length — user can send 10MB of text!
})

// Fix: always set max length
const schema = z.object({
  bio: z.string().max(5000, 'Bio must be under 5000 characters')
})

3. Trusting Hidden Form Fields

// AI sometimes generates:
<input type="hidden" name="role" value="user">

// An attacker changes this to:
<input type="hidden" name="role" value="admin">

// Server-side: NEVER trust role/permission values from the client.
// Determine the user's role from their authenticated session, not from the request body.

What to Learn Next

Frequently Asked Questions

What is input validation?

Input validation is checking that data from users (form fields, URL parameters, API request bodies) meets your expected format, length, and type before your app processes it. It's the #1 security practice because it stops most attacks — SQL injection, XSS, denial of service — at the front door.

Why do I need server-side validation if I have client-side?

Client-side validation (HTML required attributes, JavaScript checks) improves UX with instant feedback, but provides zero security. Anyone can bypass it with curl, Postman, or by disabling JavaScript. Server-side validation is the security boundary — the only validation attackers can't skip. Always validate on the server. Always.

What is the difference between validation and sanitization?

Validation checks if input is acceptable (valid email? within length? correct type?). Sanitization cleans input by removing or escaping dangerous characters (stripping HTML tags, encoding special characters). Do both: validate first to reject clearly bad data, then sanitize what passes to handle edge cases.

What library should I use for validation?

Zod is the current standard for TypeScript/JavaScript — define schemas, parse and validate in one step. Alternatives: Joi (mature, well-documented), Yup (popular with React form libraries), express-validator (middleware-based for Express). AI most commonly generates Zod as of 2026.

What does AI get wrong about validation?

AI commonly generates only client-side validation (zero security value), skips length limits (allowing massive payloads), and trusts hidden form fields for role/permission values (easily tampered). Always add server-side validation with a library like Zod, set max lengths on every field, and never determine user permissions from request body data.