dlseitz.dev-frontend/src/scripts/contact-form.js

95 lines
3.2 KiB
JavaScript

// Contact Form Submission Script
const form = document.getElementById("contact-form");
const resetButton = form.querySelector('button[type="reset"]');
// Utility: Show error for specific input
function showError(inputId, message) {
const input = document.getElementById(inputId);
const errorSpan = document.getElementById(`${inputId}-error`);
if (input) input.classList.add("error");
if (errorSpan) errorSpan.textContent = message;
}
// Utility: Clear all errors
function clearErrors() {
document.querySelectorAll(".error-message").forEach(span => span.textContent = "");
document.querySelectorAll("input, textarea").forEach(input => input.classList.remove("error"));
}
form.addEventListener("submit", function(event) {
event.preventDefault(); // Prevent actual form submission
clearErrors(); // Clear previous errors
// Get values
const firstName = document.getElementById("first-name").value.trim();
const lastName = document.getElementById("last-name").value.trim();
const organization = document.getElementById("organization").value.trim();
const email = document.getElementById("email").value.trim();
const phone = document.getElementById("phone").value.trim();
const contactMethod = document.querySelector('input[name="contact-method"]:checked')?.value;
const message = document.getElementById("message").value.trim();
let hasErrors = false;
// First Name
if (!firstName) {
showError("first-name", "Please enter your first name.");
hasErrors = true;
} else if (firstName.length < 2) {
showError("first-name", "First name must be at least 2 characters.");
hasErrors = true;
}
// Last Name
if (!lastName) {
showError("last-name", "Please enter your last name.");
hasErrors = true;
} else if (lastName.length < 2) {
showError("last-name", "Last name must be at least 2 characters.");
hasErrors = true;
}
// Organization (optional)
if (organization.length > 0 && organization.length < 2) {
showError("organization", "Organization name must be at least 2 characters.");
hasErrors = true;
}
// Email
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
showError("email", "Please enter a valid email address.");
hasErrors = true;
}
// Phone — match format: 123-456-7890
const phonePattern = /^\d{3}-\d{3}-\d{4}$/;
if (!phonePattern.test(phone)) {
showError("phone", "Phone number must be in the format 123-456-7890.");
hasErrors = true;
}
// Message
if (message.length < 10) {
showError("message", "Message must be at least 10 characters long.");
hasErrors = true;
}
if (!hasErrors) {
alert("Form submitted successfully!");
// form.submit(); // Uncomment when ready to send to server
}
});
form.addEventListener("reset", function (event) {
const confirmed = confirm("Are you sure you want to clear the form?");
if (!confirmed) {
event.preventDefault();
return;
}
clearErrors();
});