-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.ts
More file actions
42 lines (39 loc) · 1.17 KB
/
Copy pathparse.ts
File metadata and controls
42 lines (39 loc) · 1.17 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
import type { StandardSchemaV1 } from "@standard-schema/spec";
import { decode } from "./decode.js";
import { toSubmission } from "./submission.js";
import type { SchemaResult } from "./types.js";
/**
* Parses and validates FormData against a schema.
*
* @param schema A Standard Schema object.
* @param formData FormData to parse and validate.
* @returns A Standard Schema Result with a `submission()` method.
*
* @example
* ```ts
* const result = parseFormData(schema, formData);
* const submission = result.submission();
*
* if (submission.status === 'success') {
* console.log(submission.value); // Validated data
* } else {
* console.log(submission.fieldErrors); // Validation errors
* }
* ```
*/
export function parseFormData<T extends StandardSchemaV1>(
schema: T,
formData: FormData,
): SchemaResult<T> {
const input = decode<StandardSchemaV1.InferOutput<T>>(formData);
const result = schema["~standard"].validate(input);
if (result instanceof Promise) {
throw new TypeError("Schema validation must be synchronous");
}
return {
...result,
submission() {
return toSubmission<StandardSchemaV1.InferOutput<T>>(input, result);
},
};
}