Files
tm-landing/app/_contact-us/form.tsx
T
AmirReza Jamali 2182386f9c feat(contact-us): Add hCaptcha verification to contact form
- Install @hcaptcha/react-hcaptcha dependency for CAPTCHA protection
- Add hCaptcha component integration with site key configuration
- Implement captcha token state management with verification callbacks
- Add token validation before form submission with user feedback
- Reset captcha after successful form submission
- Include captcha in form submission payload as hcaptcha_token
- Update Next.js to version 15.5.7 for compatibility
- Enhance form security by requiring CAPTCHA verification before contact submission
2025-12-08 16:56:14 +03:30

184 lines
4.7 KiB
TypeScript

"use client";
import api from "@/service/api";
import HCaptcha from "@hcaptcha/react-hcaptcha";
import { useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "react-toastify";
import InputGroup from "../_components/InputGroup";
import Loading from "../_components/Loading";
import TextareaGroup from "../_components/Textarea";
type TContactUsForm = {
full_name: string;
email: string;
phone: string;
message: string;
};
interface IProps {
columnsPerRow?: 1 | 2 | 3 | 4;
buttonText?: string;
}
const ContactUsForm = ({
buttonText = "Submit",
columnsPerRow = 1,
}: IProps) => {
const [isLoading, setIsLoading] = useState(false);
const [hcaptchaToken, setHcaptchaToken] = useState<string | null>(null);
const captchaRef = useRef<HCaptcha>(null);
const {
register,
handleSubmit,
formState: { errors },
reset,
} = useForm<TContactUsForm>();
const onCaptchaVerify = (token: string) => {
setHcaptchaToken(token);
};
const onCaptchaExpire = () => {
setHcaptchaToken(null);
};
const onSubmit = async (data: TContactUsForm) => {
if (!hcaptchaToken) {
toast.error("Please complete the captcha verification");
return;
}
setIsLoading(() => true);
try {
const response = (
await api.post("contacts", { ...data, hcaptcha_token: hcaptchaToken })
).data;
toast.success(response.message);
reset();
setHcaptchaToken(null);
captchaRef.current?.resetCaptcha();
} catch (error) {
console.log(error);
toast.error("Something went wrong");
throw error;
} finally {
setIsLoading(() => false);
}
};
const gridColsClass = {
1: "lg:grid-cols-1",
2: "lg:grid-cols-2",
3: "lg:grid-cols-3",
4: "lg:grid-cols-4",
}[columnsPerRow];
const colSpanClass = {
1: "lg:col-span-1",
2: "lg:col-span-2",
3: "lg:col-span-3",
4: "lg:col-span-4",
}[columnsPerRow];
return (
<form
className={`w-full px-4 lg:px-16 py-10 grid ${gridColsClass} gap-4`}
onSubmit={handleSubmit(onSubmit)}>
<InputGroup
id="full_name"
label="Full Name"
register={register}
validation={{
required: {
message: "This field is required",
value: true,
},
minLength: {
value: 2,
message: "Please enter at least 2 characters",
},
maxLength: {
value: 100,
message: "Please enter at most 100 characters",
},
}}
type="text"
error={errors.full_name?.message}
/>
<InputGroup
id="email"
label="Email"
register={register}
validation={{
required: {
message: "This field is required",
value: true,
},
pattern: {
value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
message: "Please enter a valid email address",
},
}}
type="email"
error={errors.email?.message}
/>
<InputGroup
id="phone"
label="Phone"
register={register}
validation={{
required: {
message: "This field is required",
value: true,
},
minLength: {
value: 10,
message: "Please enter at least 10 characters",
},
maxLength: {
value: 20,
message: "Please enter at most 20 characters",
},
pattern: {
value: /^[+\d]+$/,
message: "Please enter a valid phone number",
},
}}
type="text"
error={errors.phone?.message}
/>
<TextareaGroup
id="message"
label="Message"
register={register}
error={errors.message?.message}
validation={{
required: {
value: true,
message: "This field is required",
},
maxLength: {
value: 1000,
message: "Please enter at most 1000 characters",
},
minLength: {
value: 10,
message: "Please enter at least 10 characters",
},
}}
/>
<div className={`${colSpanClass}`}>
<HCaptcha
sitekey={process.env.NEXT_PUBLIC_HCAPTCHA_SITE_KEY || ""}
onVerify={onCaptchaVerify}
onExpire={onCaptchaExpire}
ref={captchaRef}
/>
</div>
<div className={`${colSpanClass} flex justify-end`}>
<button className="bg-(--primary) cursor-pointer w-fit text-white rounded-full py-4 px-6 flex justify-center items-center text-center">
{isLoading ? <Loading /> : buttonText}
</button>
</div>
</form>
);
};
export default ContactUsForm;