Skip to content

Commit fdba18f

Browse files
committed
add formapi script for form validation
1 parent 34556f0 commit fdba18f

File tree

1 file changed

+71
-1
lines changed

1 file changed

+71
-1
lines changed

formapi/scripts/script.js

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,74 @@ window.onload = function() {
99
option.text = i;
1010
ageSelection.add(option);
1111
}
12-
};
12+
};
13+
14+
//Create formapi validation function
15+
document.getElementById("userForm").addEventListener("submit", function(event){
16+
//Prevent regular form submission
17+
event.preventDefault();
18+
19+
//Get the form
20+
const form = event.target;
21+
22+
//Create a form data object
23+
const userFormData = new FormData(form);
24+
25+
//Create a isvalid variable
26+
let isValid = true;
27+
28+
//Create an error message array
29+
const errorMessage = [];
30+
31+
//Create email validation
32+
const emailFormField = form.querySelector("#email");
33+
if (!emailFormField.value.includes("@")) {
34+
isValid = false;
35+
36+
//Create an error message and push to array
37+
errorMessage.push("Please enter a valid email address.");
38+
}
39+
40+
//Create phone number validation
41+
const phoneNumberFormField = form.querySelector("#phoneNumber");
42+
43+
//Create a regex for phone number validation
44+
const phoneNumberRegex = /^\d{3}-\d{3}-\d{4}$/;
45+
if (!phoneNumberRegex.test(phoneNumberFormField.value)) {
46+
isValid = false;
47+
48+
//Create an error message and push to array
49+
errorMessage.push("Please enter a valid phone number format (xxx-xxx-xxxx).");
50+
}
51+
52+
//Create address validation
53+
const addressFormField = form.querySelector("#address");
54+
55+
//Create a regex for address validation
56+
const addressRegex = /^[a-zA-Z0-9\s,'-]*$/;
57+
if (!addressRegex.test(addressFormField.value)) {
58+
isValid = false;
59+
60+
//Create an error message and push to array
61+
errorMessage.push("Please enter a valid Street address.");
62+
}
63+
64+
65+
//Show the form validation errors
66+
if (!isValid) {
67+
alert(errorMessage[0]);
68+
return;
69+
}
70+
71+
//Create an if statement to check if form submitted is valid
72+
if (form.checkValidity()) { //Use checkValidity from Form API to validate form
73+
//Create an alert that the form is valid
74+
alert("Form Submitted Successfully!");
75+
76+
//Reset the form
77+
form.reset();
78+
} else {
79+
//Show form validation errors
80+
form.reportValidity();
81+
}
82+
});

0 commit comments

Comments
 (0)