Skip to content

Commit

Permalink
validation put into separate file to make code more clear
Browse files Browse the repository at this point in the history
  • Loading branch information
Fermatka committed Mar 25, 2024
1 parent 77c6063 commit c43b334
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 17 deletions.
21 changes: 4 additions & 17 deletions algrtm/src/components/ContactFormContainer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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;
}

Expand Down
21 changes: 21 additions & 0 deletions algrtm/src/utils/validation.js
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit c43b334

Please sign in to comment.