( form: HTMLFormElement, initialValue?: T, )
| 16 | element instanceof HTMLSelectElement; |
| 17 | |
| 18 | export function formToJson<T extends Record<string, unknown>>( |
| 19 | form: HTMLFormElement, |
| 20 | initialValue?: T, |
| 21 | ): T { |
| 22 | const initialData = (initialValue ?? {}) as FormValues; |
| 23 | |
| 24 | const values = Array.from(form.elements).reduce<FormValues>( |
| 25 | (acc, element) => { |
| 26 | if (!isFormFieldElement(element) || element.name === '') { |
| 27 | return acc; |
| 28 | } |
| 29 | |
| 30 | // Handle fields that end with [] as arrays. |
| 31 | if (element.name.endsWith('[]')) { |
| 32 | const fieldName = element.name.slice(0, -2); |
| 33 | const existingValue = acc[fieldName]; |
| 34 | const existingArray = Array.isArray(existingValue) ? existingValue : []; |
| 35 | |
| 36 | if (element.value && element.value.trim().length > 0) { |
| 37 | return { ...acc, [fieldName]: [...existingArray, element.value] }; |
| 38 | } |
| 39 | |
| 40 | return acc; |
| 41 | } |
| 42 | |
| 43 | if (element instanceof HTMLInputElement && element.type === 'checkbox') { |
| 44 | return { ...acc, [element.name]: element.checked }; |
| 45 | } |
| 46 | |
| 47 | if ( |
| 48 | element instanceof HTMLInputElement && |
| 49 | element.type === 'radio' && |
| 50 | !element.checked |
| 51 | ) { |
| 52 | return acc; |
| 53 | } |
| 54 | |
| 55 | if (element instanceof HTMLInputElement && element.type === 'file') { |
| 56 | const { files } = element; |
| 57 | return { |
| 58 | ...acc, |
| 59 | [element.name]: !files || files.length === 0 ? null : files, |
| 60 | }; |
| 61 | } |
| 62 | |
| 63 | return { |
| 64 | ...acc, |
| 65 | [element.name]: element.value.length ? element.value : null, |
| 66 | }; |
| 67 | }, |
| 68 | initialData, |
| 69 | ); |
| 70 | |
| 71 | return values as unknown as T; |
| 72 | } |
| 73 | |
| 74 | export const applyZodErrorsToForm = <TFieldValues extends FieldValues>({ |
| 75 | error: originalError, |
no test coverage detected