import type { ContactData, ContactErrorCode, ContactField, FieldType } from '../types' const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ const DEFAULT_MAX: Record = { text: 200, email: 254, tel: 50, url: 2048, textarea: 5000, select: 200, } export type ValidationResult = | { ok: true; data: ContactData } | { ok: false; code: ContactErrorCode } /** * Validate + normalize a raw request body against the field schema. * * - Trims every value; lowercases emails. * - Enforces `required`, per-field `maxLength` (with type defaults), * email format, and that `select` values are one of the declared options. * - Returns a clean `ContactData` containing exactly the configured fields * (so nothing the client sends outside the schema is ever persisted/emailed). */ export function validateContact( fields: ReadonlyArray, body: Record ): ValidationResult { const data: ContactData = {} for (const field of fields) { const type = field.type ?? 'text' const raw = body[field.name] let value = typeof raw === 'string' ? raw.trim() : raw == null ? '' : String(raw).trim() if (type === 'email') value = value.toLowerCase() if (field.required && value === '') { return { ok: false, code: 'missing_fields' } } if (value !== '') { const max = field.maxLength ?? DEFAULT_MAX[type] if (value.length > max) { return { ok: false, code: 'too_long' } } if (type === 'email' && !EMAIL_RE.test(value)) { return { ok: false, code: 'invalid_email' } } if ( type === 'select' && field.options && !field.options.some((option) => option.value === value) ) { return { ok: false, code: 'invalid_request' } } } data[field.name] = value } return { ok: true, data } }