forked from Lilly-Protocol/lily-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidation.ts
More file actions
49 lines (43 loc) · 1.33 KB
/
Copy pathvalidation.ts
File metadata and controls
49 lines (43 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { z, type ZodSchema, type ZodError } from "zod";
export type FieldErrors = Record<string, string[]>;
export interface ValidationResult<T> {
success: boolean;
data?: T;
fieldErrors?: FieldErrors;
}
/**
* Validates untrusted input against a Zod schema and normalises the result
* into a shape compatible with `useFormAction` and server actions.
*/
export function validate<T>(
schema: ZodSchema<T>,
input: unknown,
): ValidationResult<T> {
const result = schema.safeParse(input);
if (result.success) {
return { success: true, data: result.data };
}
const fieldErrors: FieldErrors = {};
for (const issue of result.error.issues) {
const path = issue.path.map(String).join(".") || "_form";
if (!fieldErrors[path]) {
fieldErrors[path] = [];
}
fieldErrors[path].push(issue.message);
}
return { success: false, fieldErrors };
}
/**
* Convenience helper to parse FormData into a plain object suitable for
* Zod validation. Handles single-value fields only; multi-value fields
* should be handled by the caller.
*/
export function formDataToObject(formData: FormData): Record<string, string> {
const obj: Record<string, string> = {};
formData.forEach((value, key) => {
if (typeof value === "string") {
obj[key] = value;
}
});
return obj;
}