Files
validate/sanitize.ts
2025-07-01 15:07:57 -07:00

28 lines
969 B
TypeScript

/**
* Sanitizes a FormData value by key, returning a trimmed string.
* If the key is not present, it throws an error or returns a fallback value.
* @param data - The FormData object to sanitize.
* @param key - The key to look for in the FormData.
* @param fallback - Optional fallback value to return if the key is not found.
* @returns The sanitized string value or the fallback value.
* @throws Error if the key is required and not found.
* @template Fallback - The type of the fallback value.
*/
export function sanitize(data: FormData, key: string): string;
export function sanitize<Fallback>(
data: FormData,
key: string,
fallback: Fallback
): string | Fallback;
export function sanitize<Fallback>(
data: FormData,
key: string,
fallback?: Fallback
): string | Fallback {
const val = data.get(key);
if (val !== null) return val.toString().trim();
if (fallback !== undefined) return fallback;
throw new Error(`Missing required field: ${key}`);
}