Validation

You might say

People can submit complete nonsense. How do I stop bad input before it gets saved?

Check that incoming data has the expected shape and allowed valuesA required field can be checked when someone leaves it, while cross-field rules usually need a submit-time check. Frontend feedback helps people correct mistakes, but the backend must validate again and return specific field errors.
Backend rulesDo not write if it does not pass

When to use it

  • Check API request bodies
    See field rules at a glance
    emailRequired · email formatpriceNumber · greater than 0roleuser / admin
  • Validate form submissions on the server
    Errors should point to the specific field.
    Product price-3Below the inputPrice must be greater than 0
  • Reject impossible or malformed values
    Write to the database only after validation passes
    Receive inputRule checkWrite to database
  • Return field-level errors the interface can explain
    Keep rules together in one schema
    email: string().email()price: number().positive()role: enum(["user", "admin"])

When NOT to use it

  • Trust data only because TypeScript compiled
    Page-side checks can be bypassed
    Skip formRequest API directlyBackend still needs validation
  • Validate only in the browser
    Status code and result contradict each other
    HTTP200 OKResponse bodyerror: invalid email
    The frontend can easily mistake failure for success.
  • Return one vague error for every field
    Do not show internal errors to users.
    PrismaClientKnownRequestErrorat node_modules/runtime/library.js:129:42
    The page should say: Unable to save right now. Please try again later.
  • Use validation as a substitute for authentication or authorization
    Do not silently change critical data.
    User inputPrice -99 System silently changes it toPrice 99
    Reject it clearly and ask the user to confirm.
Anatomy
Original inputValidation rulesPassorField error
Forms, URLs, headers, and third parties are all untrusted input.
Define types, required fields, ranges, lengths, and allowed values.
Passing proves schema conformance; authorization, business rules, and output context still need checks.
Typical use cases
Registration
Registration VerificationDescribe how to modify next to the field
Create account
Incomplete email format · Password must be at least 8 characters
Order creation
Product priceReject unreasonable values
Verification resultThe price must be greater than 0
Profile update
Article titleShow length limit when typing
Currently56 wordsMaximum40 words
Webhook input
Request body SchemaValidate API fields in one place
email✓ stringage✕ Should be 1–120role✓ user
Failure will return 400 or 422 and field-level errors according to API convention
Further reading