switch·Esc back

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 valuesValidation verifies required fields, types, formats, lengths, and cross-field rules before data is used or stored. The frontend can help users correct mistakes early, but the backend must validate again because requests can bypass the interface.
Backend rulesDo not write if it does not pass

When to use it

  • Check API request bodies
  • Validate form submissions on the server
  • Reject impossible or malformed values
  • Return field-level errors the interface can explain

When NOT to use it

  • Trust data only because TypeScript compiled
  • Validate only in the browser
  • Return one vague error for every field
  • Use validation as a substitute for authentication or authorization
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