-
Notifications
You must be signed in to change notification settings - Fork 0
/
Test_Html_Js
50 lines (38 loc) · 1.22 KB
/
Test_Html_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
<form id="contact-form">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
<button type="submit">Submit</button>
</form>
const form = document.getElementById('contact-form');
form.addEventListener('submit', (event) => {
event.preventDefault();
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const message = document.getElementById('message').value;
if (!validateEmail(email)) {
alert('Please enter a valid email address.');
return;
}
const xhr = new XMLHttpRequest();
xhr.open('POST', '/submit-form');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
alert('Your message has been sent!');
form.reset();
}
};
xhr.send(JSON.stringify({
name: name,
email: email,
message: message
}));
});
function validateEmail(email) {
const regex = /^([a-zA-Z0-9_\.-]+)@([a-zA-Z0-9_\.-]+)\.([a-zA-Z]{2,5})$/;
return regex.test(email);
}