Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Standardize forms on React Hook Form + Zod
Use React Hook Form for state management and Zod for schemas so validation and error handling are consistent.
Bad example
| 1 | import { useState } from "react"; |
| 2 |
|
| 3 | export function Signup() { |
| 4 | const [email, setEmail] = useState(""); |
| 5 | const [error, setError] = useState<string | null>(null); |
| 6 |
|
| 7 | const onSubmit = () => { |
| 8 | if (!email.includes("@")) { |
| 9 | setError("Invalid email"); |
| 10 | return; |
| 11 | } |
| 12 | // submit |
| 13 | }; |
| 14 |
|
| 15 | return ( |
| 16 | <form onSubmit={onSubmit}> |
| 17 | <input value={email} onChange={(e) => setEmail(e.target.value)} /> |
| 18 | {error ? <p>{error}</p> : null} |
| 19 | </form> |
| 20 | ); |
| 21 | } |
Explanation (EN)
Hand-rolled validation logic diverges across forms and is easy to forget. It also makes type inference and error handling inconsistent.
Objašnjenje (HR)
Ručna validacija se lako razilazi između formi i često se zaboravi. Tipovi i error handling postaju nekonzistentni.
Good example
| 1 | import { useForm } from "react-hook-form"; |
| 2 | import { z } from "zod"; |
| 3 | import { zodResolver } from "@hookform/resolvers/zod"; |
| 4 |
|
| 5 | const SignupSchema = z.object({ |
| 6 | email: z.string().email() |
| 7 | }); |
| 8 |
|
| 9 | type SignupValues = z.infer<typeof SignupSchema>; |
| 10 |
|
| 11 | export function Signup() { |
| 12 | const form = useForm<SignupValues>({ |
| 13 | resolver: zodResolver(SignupSchema), |
| 14 | mode: "onSubmit", |
| 15 | reValidateMode: "onBlur", |
| 16 | }); |
| 17 |
|
| 18 | return ( |
| 19 | <form onSubmit={form.handleSubmit(() => {})}> |
| 20 | <input {...form.register("email")} /> |
| 21 | </form> |
| 22 | ); |
| 23 | } |
Explanation (EN)
RHF + Zod centralize validation and keep form state predictable. The schema becomes the single source of truth for types and errors.
Objašnjenje (HR)
RHF + Zod centraliziraju validaciju i drže stanje forme predvidljivim. Shema postaje jedini izvor istine za tipove i greške.
Notes (EN)
Prefer validation on submit + blur (mode: onSubmit, reValidateMode: onBlur).
Bilješke (HR)
Preferiraj validaciju na submit + blur (mode: onSubmit, reValidateMode: onBlur).
Exceptions / Tradeoffs (EN)
Live validation is acceptable when UX requires immediate feedback.
Iznimke / Tradeoffi (HR)
Live validacija je prihvatljiva kada UX zahtijeva trenutni feedback.