/** * Author: Simon-Pierre Boucher * Contact: contact@spboucher.ai * Project: Hilmacorp.ai — Web Platform * File: lib/validate.ts * Description: Pure validation logic for the contact form (shared by the API route and tests) */ export interface ContactPayload { name: string; organization: string; email: string; message: string; } export interface ValidationResult { ok: boolean; errors: Partial>; data?: ContactPayload; } const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/; const MAX_FIELD = 500; const MAX_MESSAGE = 5000; function clean(value: unknown, max: number): string { if (typeof value !== "string") return ""; return value.trim().slice(0, max); } export function validateContact(input: unknown): ValidationResult { const raw = (input ?? {}) as Record; const data: ContactPayload = { name: clean(raw.name, MAX_FIELD), organization: clean(raw.organization, MAX_FIELD), email: clean(raw.email, MAX_FIELD), message: clean(raw.message, MAX_MESSAGE), }; const errors: ValidationResult["errors"] = {}; if (data.name.length < 2) errors.name = "invalid_name"; if (!EMAIL_RE.test(data.email)) errors.email = "invalid_email"; if (data.message.length < 10) errors.message = "invalid_message"; const ok = Object.keys(errors).length === 0; return ok ? { ok, errors, data } : { ok, errors }; }