-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
70 lines (55 loc) · 2.41 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
function toggleMenu() {
const menu = document.querySelector(".menu-links");
const icon = document.querySelector(".hamburger-icon");
menu.classList.toggle("open");
icon.classList.toggle("open");
}
document.getElementById("contact-form").addEventListener("submit", (event) => {
const contactForm = event.target
if (!validateContactForm(contactForm)) {
event.preventDefault();
displayError(contactForm, 'Invalid input')
}
});
// Function to validate email addresses
function isValidEmail(email) {
// Define the JS Regex pattern for a valid email address
const emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
// Test the email against the pattern and return the result (true or false)
return emailRegex.test(email);
}
// Function to validate phone numbers
function isValidPhoneNumber(phone) {
// Define the JS Regex pattern for a valid 10-digit phone number
const phoneRegex = /^\d{10}$/;
// Test the phone number against the pattern and return the result (true or false)
return phoneRegex.test(phone);
}
// Function to validate the contact form
function validateContactForm(contactForm) {
// Get the values entered in the form fields
const name = contactForm["name"].value;
const email = contactForm["email"].value;
const message = contactForm["message"].value;
// Check if the required fields (name, email, and message) are empty
// If any of them are empty, return false to prevent form submission
if (!name || !email || !message) {
return false;
}
// Check if the email is valid using the isValidEmail function
// If the phone field is not empty, also check if it is valid using the isValidPhoneNumber function
// If either the email or the phone number is invalid, return false to prevent form submission
if (!isValidEmail(email)) {
return false;
}
// If all the validations pass, return true to allow form submission
return true;
}
// Function to display an error message on the web page
function displayError(formElement, message) {
const errorElement = formElement.getElementsByClassName("form-error")[0];
// Set the innerHTML of the error element to the provided error message
errorElement.innerHTML = message;
// Change the display style of the error element to "block" to make it visible
errorElement.style.display = "block";
}