Mateusz• 40
@MateuszSobiech
Posted
"What specific areas of your project would you like help with? - The javascript"
What would you like to know?
0
Salim TOURE• 240
@limsael
Posted
@MateuszSobiech A better way to handle forms
0
Mateusz• 40
@MateuszSobiech
Posted
@limsael
const body = document.body;
const form = document.querySelector("form");
const emailInput = document.querySelector("#email");
const formMessage = document.querySelector("#form-message");
const formSuccess = document.querySelector("#form-success");
const dismissBtn = document.querySelector("#dismiss-btn");
const userEmail = document.querySelector("#user-email");
const emailRegex = /^[A-Za-z\._\-0-9]*[@][A-Za-z]*[\.][a-z]{2,4}$/;
const showThanksView = (emailValue) =>{
body.classList.add("success")
userEmail.textContent = emailValue;
}
const hideThanksView = () => {
body.classList.remove("success");
userEmail.textContent = ''
}
const validateForm = () => {
const emailValue = emailInput.value;
if (emailValue === "") {
return { invalid: true, message: 'Please enter your email address.' }
}
if (!emailValue.match(emailRegex)) {
return { invalid: true, message: 'Valid email required.' }
}
return { invalid: false, message: '', emailValue: emailValue }
}
form.addEventListener("submit", (event) => {
event.preventDefault();
const validResult = validateForm()
formMessage.textContent = validResult.message;
if(validResult.invalid) {
return;
}
showThanksView(validResult.emailValue)
form.reset();
});
dismissBtn.addEventListener("click", hideThanksView);
1