Skip to content

Commit

Permalink
feat: added error message field to the inputfield component
Browse files Browse the repository at this point in the history
  • Loading branch information
keyurparalkar committed Apr 14, 2024
1 parent e637093 commit f6816c2
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 6 deletions.
10 changes: 8 additions & 2 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ const FormValues = schema.fields.reduce((acc, currValue) => {
type TFormValues = typeof FormValues;

function App() {
const { register, handleSubmit } = useForm<TFormValues>();
const {
register,
handleSubmit,
formState: { errors },
} = useForm<TFormValues>();

const onSubmit = (data: TFormValues) => {
console.log("form Data = ", data);
Expand All @@ -36,7 +40,9 @@ function App() {
register={register}
labelText={field.fieldName}
htmlFor={field.accessorKey}
type={field.type}
type={field.dataType}
validation={field.validation}
error={errors[field.accessorKey]}
/>
)
)}
Expand Down
17 changes: 14 additions & 3 deletions src/components/fields/InputField.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,31 @@
import { UseFormRegister } from "react-hook-form";
import { FieldError, UseFormRegister } from "react-hook-form";
import { Input, InputProps } from "../ui/input";
import { Label } from "../ui/label";
import { TField } from "@/interfaces/field";

interface InputFieldProps extends InputProps {
labelText: string;
htmlFor: string;
register: UseFormRegister<any>;
validation?: TField["validation"];
error?: FieldError;
}

const InputField = (props: InputFieldProps) => {
const { htmlFor, register, labelText, ...rest } = props;
const { htmlFor, register, labelText, validation, error, ...rest } = props;
console.log({ htmlFor, validation });
return (
<>
<div className="flex flex-col space-y-2">
<Label htmlFor={htmlFor}>{labelText}</Label>
<Input id="htmlFor" {...rest} {...register(htmlFor)} />
<Input
id="htmlFor"
{...rest}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
{...register(htmlFor, { ...validation })}
/>
{error && <span>{error.message}</span>}
</div>
</>
);
Expand Down
2 changes: 2 additions & 0 deletions src/interfaces/field.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,5 @@ export const FieldTypeDef = z.object({
})
.optional(),
});

export type TField = z.infer<typeof FieldTypeDef>;
8 changes: 7 additions & 1 deletion src/schemas/forms/personal_info.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,13 @@
"type": "field",
"dataType": "email",
"fieldName": "Email Address",
"accessorKey": "email"
"accessorKey": "email",
"validation": {
"required": {
"value": true,
"message": "Email Address is required"
}
}
}
]
}

0 comments on commit f6816c2

Please sign in to comment.