feat(inquiries): Improve form submission validation and data sanitization
- Sanitize form data by trimming whitespace from string inputs - Implement validation for required fields with user feedback for empty inputs - Enhance error handling by displaying messages for invalid form fields - Update API submission to use sanitized data while maintaining hcaptcha token integration
This commit is contained in:
+33
-3
@@ -79,8 +79,35 @@ const InquiresForm = ({
|
||||
setHcaptchaToken(null);
|
||||
};
|
||||
const onSubmit = async (data: TInquiresForm) => {
|
||||
const isFormValid = await trigger();
|
||||
const sanitizedData = Object.fromEntries(
|
||||
Object.entries(data).map(([key, value]) => [
|
||||
key,
|
||||
typeof value === "string" ? value.trim() : value,
|
||||
]),
|
||||
) as TInquiresForm;
|
||||
|
||||
const requiredFields = fields.filter((field) => field.required);
|
||||
let hasEmptyRequiredField = false;
|
||||
|
||||
requiredFields.forEach((field) => {
|
||||
const value = sanitizedData[field.name];
|
||||
if (!value) {
|
||||
setError(field.name, {
|
||||
type: "required",
|
||||
message: `${field.label} is required`,
|
||||
});
|
||||
hasEmptyRequiredField = true;
|
||||
}
|
||||
});
|
||||
|
||||
if (hasEmptyRequiredField) {
|
||||
toast.error("Please complete all required fields");
|
||||
return;
|
||||
}
|
||||
|
||||
const isFormValid = await trigger(formFieldNames);
|
||||
if (!isFormValid) {
|
||||
toast.error("Please correct invalid form fields");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -91,7 +118,10 @@ const InquiresForm = ({
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const response = (
|
||||
await api.post("inquiries", { ...data, hcaptcha_token: hcaptchaToken })
|
||||
await api.post("inquiries", {
|
||||
...sanitizedData,
|
||||
hcaptcha_token: hcaptchaToken,
|
||||
})
|
||||
).data;
|
||||
toast.success(response.message);
|
||||
reset();
|
||||
@@ -224,7 +254,7 @@ const InquiresForm = ({
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!isValid || isLoading || !hcaptchaToken}
|
||||
className="bg-(--primary) cursor-pointer w-fit text-white rounded-full py-4 px-6 disabled:opacity-60 disabled:cursor-not-allowed">
|
||||
className="bg-(--primary) cursor-pointer inline-flex items-center justify-center min-h-14 w-fit text-white rounded-full py-4 px-6 disabled:opacity-60 disabled:cursor-not-allowed">
|
||||
{isLoading ? <Loading /> : submitText}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user