From 9f1fabc04358d02541cb9da47bf31cf64c4b236e Mon Sep 17 00:00:00 2001 From: Matthieu Jacq <67386567+matthieujacq@users.noreply.github.com> Date: Mon, 23 Oct 2023 14:06:04 +0200 Subject: [PATCH] feat: validate email and required question with react-hook-form (#1463) ## Linked to Epic: #1232 Issue: #1454 ## Description Validate required fields and email pattern using react-hook-form. --- .../app/contact/components/ContactForm.tsx | 36 +++++++++++-------- frontend/app/contact/page.tsx | 2 +- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/frontend/app/contact/components/ContactForm.tsx b/frontend/app/contact/components/ContactForm.tsx index 2bce68a94..a619a4739 100644 --- a/frontend/app/contact/components/ContactForm.tsx +++ b/frontend/app/contact/components/ContactForm.tsx @@ -1,19 +1,23 @@ import React, { useState } from "react"; +import { FieldValues, SubmitHandler, useForm } from "react-hook-form"; import { useTranslation } from "react-i18next"; import { LuChevronRight } from "react-icons/lu"; import Button from "@/lib/components/ui/Button"; export const ContactForm = (): JSX.Element => { - const [email, setEmail] = useState(""); - const [message, setMessage] = useState(""); const [submitted, setSubmitted] = useState(false); const { t } = useTranslation("contact", { keyPrefix: "form" }); - const handleSubmit = (ev: React.FormEvent) => { - ev.preventDefault(); + const { register, handleSubmit, formState } = useForm({ + defaultValues: { email: "", message: "" }, + }); + + const emailPattern = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i; + + const onSubmit: SubmitHandler = (data) => { setSubmitted(true); - console.log("submitting", email, message); + console.log("submitting", data.email, data.message); }; if (submitted) { @@ -26,7 +30,10 @@ export const ContactForm = (): JSX.Element => { } return ( -
+ void handleSubmit(onSubmit)()} + >
setEmail(ev.target.value)} + {...register("email", { + pattern: emailPattern, + required: true, + })} placeholder="jane@example.com" className="col-span-2 bg-[#FCFAF6] rounded-md p-2" - required />