From c43b3348d5e1e6cb2c6e46e1e23e0ff57833bf9c Mon Sep 17 00:00:00 2001 From: Fermatka Date: Mon, 25 Mar 2024 12:35:44 +0100 Subject: [PATCH] validation put into separate file to make code more clear --- algrtm/src/components/ContactFormContainer.js | 21 ++++--------------- algrtm/src/utils/validation.js | 21 +++++++++++++++++++ 2 files changed, 25 insertions(+), 17 deletions(-) create mode 100644 algrtm/src/utils/validation.js diff --git a/algrtm/src/components/ContactFormContainer.js b/algrtm/src/components/ContactFormContainer.js index 617a030f..e6aad353 100644 --- a/algrtm/src/components/ContactFormContainer.js +++ b/algrtm/src/components/ContactFormContainer.js @@ -2,6 +2,7 @@ import React, { useRef, useState } from "react"; import emailjs from "@emailjs/browser"; import FormField from "./shared/FormField"; +import validateForm from "@/utils/validation"; const ContactFormContainer = () => { const form = useRef(); @@ -14,24 +15,10 @@ const ContactFormContainer = () => { const email = e.target.your_email.value; const message = e.target.message.value; - const errors = {}; + const validationErrors = validateForm(name, email, message); - if (!name) { - errors.your_name = "Name field cannot be empty"; - } - - if (!email) { - errors.your_email = "Email field cannot be empty"; - } else if (!/\S+@\S+\.\S+/.test(email)) { - errors.your_email = "Invalid email address"; - } - - if (!message) { - errors.message = "Message field cannot be empty"; - } - - if (Object.keys(errors).length > 0) { - setErrors(errors); + if (Object.keys(validationErrors).length > 0) { + setErrors(validationErrors); return; } diff --git a/algrtm/src/utils/validation.js b/algrtm/src/utils/validation.js new file mode 100644 index 00000000..7587e279 --- /dev/null +++ b/algrtm/src/utils/validation.js @@ -0,0 +1,21 @@ +const validateForm = (name, email, message) => { + const errors = {}; + + if (!name) { + errors.your_name = "Name field cannot be empty"; + } + + if (!email) { + errors.your_email = "Email field cannot be empty"; + } else if (!/\S+@\S+\.\S+/.test(email)) { + errors.your_email = "Invalid email address"; + } + + if (!message) { + errors.message = "Message field cannot be empty"; + } + + return errors; +}; + +export default validateForm;