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.
Know first
When to use it
- Check API request bodiesSee field rules at a glanceemailRequired · email formatpriceNumber · greater than 0roleuser / admin
- Validate form submissions on the serverErrors should point to the specific field.Product price-3Below the inputPrice must be greater than 0
- Reject impossible or malformed valuesWrite to the database only after validation passesReceive input→Rule check→Write to database
- Return field-level errors the interface can explainKeep rules together in one schemaemail: string().email()price: number().positive()role: enum(["user", "admin"])
When NOT to use it
- Trust data only because TypeScript compiledPage-side checks can be bypassedSkip form→Request API directly→Backend still needs validation
- Validate only in the browserStatus code and result contradict each otherHTTP200 OKResponse bodyerror: invalid emailThe frontend can easily mistake failure for success.
- Return one vague error for every fieldDo not show internal errors to users.PrismaClientKnownRequestErrorat node_modules/runtime/library.js:129:42The page should say: Unable to save right now. Please try again later.
- Use validation as a substitute for authentication or authorizationDo not silently change critical data.User inputPrice -99 → System silently changes it toPrice 99Reject it clearly and ask the user to confirm.
Anatomy
Original input→Validation rules→PassorField 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
