-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontact.js
88 lines (80 loc) · 2.43 KB
/
contact.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
function validateContactForm() {
if (!checkLoginStatus()) {
return;
}
const firstName = document.getElementById("firstName").value;
const lastName = document.getElementById("lastName").value;
const phone = document.getElementById("phone").value;
const email = document.getElementById("email").value;
const gender = document.querySelector('input[name="gender"]:checked');
const comment = document.getElementById("comment").value;
const nameRegex = /^[A-Z][a-z]+$/;
const phoneRegex = /^\(\d{3}\)\s\d{3}-\d{4}$/;
const emailRegex = /\S+@\S+\.\S+/;
// Validation checks
if (!nameRegex.test(firstName)) {
alert("First name should start with a capital letter and contain only letters.");
return;
}
if (!nameRegex.test(lastName)) {
alert("Last name should start with a capital letter and contain only letters.");
return;
}
if (firstName === lastName) {
alert("First name and last name cannot be the same.");
return;
}
if (!phoneRegex.test(phone)) {
alert("Phone number must be in the format (ddd) ddd-dddd.");
return;
}
if (!emailRegex.test(email)) {
alert('Email must contain "@" and "."');
return;
}
if (!gender) {
alert("Please select a gender.");
return;
}
if (comment.trim().length < 10) {
alert("Comment must be at least 10 characters.");
return;
}
const commentID = `CMT${Date.now()}`;
// Create XML string
const xmlString = `
<commentData>
<commentID>${commentID}</commentID>
<firstName>${firstName}</firstName>
<lastName>${lastName}</lastName>
<phone>${phone}</phone>
<email>${email}</email>
<gender>${gender.value}</gender>
<comment>${comment}</comment>
</commentsData>`;
// Send XML data to the PHP file
fetch('save_xml.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `xmlData=${encodeURIComponent(xmlString)}`
})
.then(response => response.text())
.then(data => {
alert(data);
document.getElementById("contactForm").reset();
})
.catch(error => {
console.error('Error saving XML data:', error);
});
}
function checkLoginStatus() {
const authToken = localStorage.getItem('authToken');
if (!authToken) {
alert('You need to login first!');
window.location.href = 'login.html';
return false;
}
return true;
}