import React, { useState } from "react"; import "./FormField.css"; interface FormFieldProperties { type?: "text" | "email" | "password" | "number" | "tel" | "url" | "search"; placeholder?: string; value: string; onChange: (e: React.ChangeEvent) => void; required?: boolean; errorMessage?: string; showError?: boolean; onBlur?: (e: React.FocusEvent) => void; onFocus?: (e: React.FocusEvent) => void; className?: string; disabled?: boolean; autoComplete?: string; customValidator?: (value: string) => string | null; showErrorInitially?: boolean; icon?: React.ComponentType>; } const FormField: React.FC = ({ type = "text", placeholder, value, onChange, required = false, errorMessage = "Please fill out this field", showError = false, onBlur, onFocus, className = "", disabled = false, autoComplete = "off", customValidator, showErrorInitially = false, icon: Icon, }) => { const [touched, setTouched] = useState(showErrorInitially); const [customError, setCustomError] = useState(""); const validateField = (value: string): string => { if (required && !value) { return errorMessage; } if (customValidator) { const customValidation = customValidator(value); if (customValidation) { return customValidation; } } return ""; }; const shouldShowError = showError || (touched && validateField(value)); const handleBlur = (e: React.FocusEvent): void => { setTouched(true); const error = validateField(value); setCustomError(error); onBlur?.(e); }; const handleFocus = (e: React.FocusEvent): void => { setCustomError(""); onFocus?.(e); }; return (
{Icon && (
)} {shouldShowError && (
{customError || errorMessage}
)}
); }; export default FormField;