build improvements
This commit is contained in:
53
yoga-app/src/util/form-util.ts
Normal file
53
yoga-app/src/util/form-util.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import {ValidateFunction} from "ajv";
|
||||
|
||||
export type FormControl = {
|
||||
name: string,
|
||||
value?: string,
|
||||
error?: string
|
||||
}
|
||||
|
||||
export function formDataToJson(formData: FormData) {
|
||||
const object: Record<string, string | string[] | File | File[]> = {};
|
||||
formData.forEach((value, key) => {
|
||||
if ( key == 'formState'){
|
||||
return;
|
||||
}
|
||||
// Reflect.has in favor of: object.hasOwnProperty(key)
|
||||
if (!Reflect.has(object, key)) {
|
||||
object[key] = value;
|
||||
return;
|
||||
}
|
||||
if (!Array.isArray(object[key])) {
|
||||
object[key] = [];
|
||||
}
|
||||
if (value instanceof File) {
|
||||
(object[key] as File[]).push(value);
|
||||
} else {
|
||||
(object[key] as string[]).push(value);
|
||||
}
|
||||
});
|
||||
return object;
|
||||
}
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
export function copyFormValues(form: Record<string, FormControl|string|any>,jsonFormData: Record<string, FormDataEntryValue>){
|
||||
const keys = Object.getOwnPropertyNames(form);
|
||||
for(const key of keys){
|
||||
if (key == 'formState'){
|
||||
continue;
|
||||
}
|
||||
const formControl: FormControl = form[key];
|
||||
formControl.value = jsonFormData[key] as string;
|
||||
|
||||
}
|
||||
}
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
export function copyValidationErrors(form: Record<string, FormControl|string|any >,validateFunction: ValidateFunction){
|
||||
const keys = Object.getOwnPropertyNames(form);
|
||||
for(const key of keys){
|
||||
const formControl: FormControl = form[key];
|
||||
if ( key == 'formState') continue;
|
||||
formControl.error = validateFunction.errors?.find( err => err.instancePath =="/"+key)?.message;
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user