diff --git a/src/app/components/forms/TextInputField/TextInputField.tsx b/src/app/components/forms/TextInputField/TextInputField.tsx index 3aeeddc..e0d722a 100644 --- a/src/app/components/forms/TextInputField/TextInputField.tsx +++ b/src/app/components/forms/TextInputField/TextInputField.tsx @@ -1,14 +1,18 @@ import type { FieldValues, RegisterOptions, - UseFormReturn + UseFormReturn, + FieldError, + ValidationValueMessage } from "react-hook-form" import { + ErrorMessage, Field, Label, TextInput, TextInputProps } from "@amsterdam/design-system-react" +import { getValueByPath } from "app/utils/getValueByPath" type Props = { name: string @@ -26,19 +30,37 @@ export const TextInputField: React.FC = ({ formMethods = {}, ...rest }) => { - const { formState, register } = formMethods as UseFormReturn - const error = formState?.errors?.[name] + const { formState, register, setError, clearErrors, trigger, setValue } = + formMethods as UseFormReturn + const error = getValueByPath(formState?.errors, name) as FieldError const hasError = !!error + const handleValidation = (e: React.ChangeEvent) => { + const value = e.target.value + setValue(name, value) + const pattern = validation?.pattern as ValidationValueMessage + const regex = pattern?.value + const message = pattern?.message || "Ongeldige invoer" + if (!value || !regex) return + if (regex.test(value)) { + clearErrors(name) + } else { + setError(name, { type: "custom", message }) + } + void trigger() + } + return ( + {hasError && {error?.message}} ) diff --git a/src/app/pages/CaseCreatePage/CaseCreatePage.tsx b/src/app/pages/CaseCreatePage/CaseCreatePage.tsx index ba73e75..7376ec1 100644 --- a/src/app/pages/CaseCreatePage/CaseCreatePage.tsx +++ b/src/app/pages/CaseCreatePage/CaseCreatePage.tsx @@ -66,7 +66,7 @@ export const CaseCreatePage: React.FC = () => { ) : (
= ({ formMethods }) => { @@ -40,12 +48,12 @@ export const ContactsFormFields: React.FC = ({ formMethods }) => { validation={ emailValidation } formMethods={ formMethods } /> - + +type Value = boolean | string | object + +export function getValueByPath( + obj: T, + path: Path, + defaultValue?: R +): R | Value { + if (!obj || !path) return defaultValue as R + + const pathArray = Array.isArray(path) + ? path + : path.replace(/\[(\d+)]/g, ".$1").split(".") + + let current: Value = obj + + for (const key of pathArray) { + if (current && typeof current === "object" && key in current) { + current = (current as Record)[key] + } else { + return defaultValue as R + } + } + + return current +}