// Universal Validation Layer using Zod (TypeScript-first, runtime + compile-time safe)
// Why Zod? Modern, inferable types, great for shared schemas between FE/BE.
// Deterministic Error Mapping: Flattens ZodError to { [fieldPath]: firstErrorMessage }
// Supports nested paths (e.g., 'user.address.street' -> 'user.address.street').
// Usage: Monorepo/shared package for schemas/utils, or copy-paste schemas (minimal duplication).
// ============================================
// 1. SHARED TYPES & UTILITIES
// ============================================
import { z } from 'zod';
// Shared result type
export interface ValidationResult<T> {
valid: true;
data: T;
} | {
valid: false;
errors: Record<string, string>; // Deterministic: { field.path: 'exact message' }
}
// Universal validator (use anywhere: BE services, FE forms, utils)
export function validate<T>(
schema: z.ZodSchema<T>,
data: unknown
): ValidationResult<T> {
const result = schema.safeParse(data);
if (result.success) {
return { valid: true, data: result.data };
}
return {
valid: false,
errors: mapZodErrors(result.error),
};
}
// Deterministic error mapper: Flattens ZodError to path -> first message
// Handles arrays/nested/unions predictably (first issue per path).
export function mapZodErrors(error: z.ZodError): Record<string, string> {
const errors: Record<string, string> = {};
error.issues.forEach((issue) => {
const path = issue.path.join('.'); // 'user.address.street'
if (!errors[path]) { // Deterministic: first error wins (no duplicates)
errors[path] = issue.message;
}
});
return errors;
}
// ============================================
// 2. EXAMPLE SHARED SCHEMA
// ============================================
// Define schemas once (shared package or copy to FE/BE)
export const userRegistrationSchema = z.object({
name: z
.string()
.min(1, 'Name is required')
.max(50, 'Name too long (max 50 chars)'),
email: z
.string()
.email('Invalid email format')
.toLowerCase(), // Normalization
password: z
.string()
.min(8, 'Password must be at least 8 characters')
.regex(/[A-Z]/, 'Password must contain uppercase letter')
.regex(/[^a-zA-Z0-9]/, 'Password must contain special character'),
}).strict(); // No extra fields
export type UserRegistration = z.infer<typeof userRegistrationSchema>;
// ============================================
// 3. BACKEND INTEGRATION (Node.js/Express + Zod)
// ============================================
// Install: npm i zod express @types/express
// Middleware/service layer example
import express from 'express';
import { validate, userRegistrationSchema, ValidationResult } from './validation'; // Shared
const app = express();
app.use(express.json());
// Universal validation middleware (reusable for any route)
export function validationMiddleware<T>(
schema: z.ZodSchema<T>
): express.RequestHandler {
return (req, res, next) => {
const result = validate(schema, req.body);
if (!result.valid) {
return res.status(400).json({
success: false,
errors: result.errors, // Deterministic shape
});
}
// Attach parsed data to req
(req as any).validatedBody = result.data;
next();
};
}
// API Route Example
app.post(
'/register',
validationMiddleware(userRegistrationSchema),
(req, res) => {
const user = (req as any).validatedBody as UserRegistration;
// Business logic (e.g., save to DB)
res.json({ success: true, user });
}
);
// Service layer example (non-HTTP)
export async function createUserService(data: unknown): Promise<ValidationResult<UserRegistration>> {
const result = validate(userRegistrationSchema, data);
if (!result.valid) return result;
// Further logic (e.g., DB check)
// ...
return result;
}
// Error Response Shape (always deterministic):
// {
// "success": false,
// "errors": {
// "name": "Name is required",
// "email": "Invalid email format",
// "password": "Password must be at least 8 characters"
// }
// }
// ============================================
// 4. FRONTEND INTEGRATION (React + React Hook Form + Zod)
// ============================================
// Install: npm i react-hook-form @hookform/resolvers zod
// Universal hook with mapped errors
import { useForm, UseFormReturn } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useMemo } from 'react';
import { z, ZodSchema } from 'zod';
import { validate, mapZodErrors, ValidationResult } from './validation'; // Shared
// Universal typed form hook (any schema)
export function useValidatedForm<T>(
schema: ZodSchema<T>
): UseFormReturn<T> & { serverErrors?: Record<string, string>; manualValidate: (data: T) => ValidationResult<T> } {
const form = useForm<T>({
resolver: zodResolver(schema),
mode: 'onChange', // Real-time validation
});
// Expose manual validate (e.g., for server errors)
const manualValidate = useMemo(() => (data: T) => validate(schema, data), [schema]);
return {
...form,
manualValidate,
// Getter for mapped errors (RHF + server)
getMappedErrors: () => {
const formErrors: Record<string, string> = {};
Object.entries(form.formState.errors).forEach(([key, error]) => {
if (error.message) formErrors[key] = error.message;
});
return formErrors;
},
};
}
// React Component Example
import { useState } from 'react';
import { userRegistrationSchema, UserRegistration } from './validation';
function RegisterForm() {
const [serverErrors, setServerErrors] = useState<Record<string, string>>({});
const form = useValidatedForm<UserRegistration>(userRegistrationSchema);
const onSubmit = async (data: UserRegistration) => {
// Simulate API call
const response = await fetch('/api/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
const json = await response.json();
if (!json.success) {
setServerErrors(json.errors); // Deterministic mapping matches BE
form.setError('root', { message: 'Validation failed' }); // Optional root error
return;
}
// Success
setServerErrors({});
alert('Registered!');
};
return (
<form onSubmit={form.handleSubmit(onSubmit)}>
<div>
<input {...form.register('name')} />
{form.formState.errors.name?.message && (
<p style={{ color: 'red' }}>{form.formState.errors.name.message}</p>
)}
{serverErrors.name && <p style={{ color: 'red' }}>{serverErrors.name}</p>}
</div>
<div>
<input type="email" {...form.register('email')} />
{form.formState.errors.email?.message && (
<p style={{ color: 'red' }}>{form.formState.errors.email.message}</p>
)}
{serverErrors.email && <p style={{ color: 'red' }}>{serverErrors.email}</p>}
</div>
<div>
<input type="password" {...form.register('password')} />
{form.formState.errors.password?.message && (
<p style={{ color: 'red' }}>{form.formState.errors.password.message}</p>
)}
{serverErrors.password && <p style={{ color: 'red' }}>{serverErrors.password}</p>}
</div>
<button type="submit" disabled={form.formState.isSubmitting}>
Register
</button>
</form>
);
}
// ============================================
// 5. EXTENSIONS & BEST PRACTICES
// ============================================
// Nested Schemas (auto-handles dot paths)
const nestedSchema = z.object({
user: z.object({
address: z.object({
street: z.string().min(1, 'Street required'),
}),
}),
});
// i18n: Pass message fn to schema (deterministic per locale)
const i18nSchema = z.object({
name: z.string().min(1, ({ context }) => t('name.required')), // Custom resolver
});
// SuperRefine for cross-field (still maps to paths)
userRegistrationSchema
.superRefine((data, ctx) => {
if (data.password.includes(data.name)) {
ctx.addIssue({
code: 'custom',
path: ['password'],
message: 'Password cannot contain name',
});
}
});
// Testing: 100% deterministic
// validate(schema, invalidData).errors === { expected: { ... } }
// Deployment: Bundle Zod schemas (tree-shakable, ~10KB gzipped).
// Monorepo: tsup/vite to share ./schemas & ./validation.ts between FE/BE.
// Migrate from Yup? Replace with Zod schemas (similar API, better perf/TS).
This layer is universal (same validate() & schemas everywhere), deterministic (fixed error shape/mapping), type-safe (infers T), and plug-and-play for Express/RHF. Errors match exactly BE→FE. Scale by adding schemas to a shared lib.