我正在在线学习 Javascript,我在这个验证模式表单上被阻止了。谁能帮忙?
所以我有这个表格,我必须提交,我创建了一个函数来检查输入并且它有效,然后当我提交时它没有做任何事情。
实际上我认为我必须使用带有“isFormValid”的 if 语句,但我不知道在哪里以及如何插入它。我试图在所有函数周围插入这个“isFormValid”,但由于它,表单不再检查输入......
const form = document.getElementById("form");
const successPopupClose = document.querySelector(".close-success")
const errorMsg = document.querySelectorAll(".error");
const successIcon = document.querySelectorAll(".success-icon");
const failureIcon = document.querySelectorAll(".failure-icon");
let successMsg = document.getElementById("success-popup");
let firstName = document.getElementById("first");
let lastName = document.getElementById("last");
let email = document.getElementById("email");
let birthdate = document.getElementById("birthdate");
let checkbox1 = document.getElementById("checkbox1");
let quantity = document.getElementById("quantity")
let city = document.reserve.location;
let isFormValid = false;
form.addEventListener("submit", (e) => {
e.preventDefault();
checkInputs();
// if(isFormValid) {
// modalbg.remove();
// successMsg.style.display = 'block';
})
function checkInputs() {
// Validate first name
if(firstName.value.trim() === ''){
errorMsg[0].innerHTML = 'Veuillez entrer au moins 2 caractères';
failureIcon[0].style.opacity = "1";
isFormValid = false;
} else {
errorMsg[0].innerHTML = '';
failureIcon[0].style.opacity = "0";
successIcon[0].style.opacity = "1";
isFormValid = true;
}
// Validate last name
if(lastName.value.trim() === ''){
errorMsg[1].innerHTML = 'Veuillez entrer au moins 2 caractères';
failureIcon[1].style.opacity = "1";
isFormValid = false;
} else {
errorMsg[1].innerHTML = '';
failureIcon[1].style.opacity = "0";
successIcon[1].style.opacity = "1";
isFormValid = true;
}
// Validate email name
if(email.value.trim() === ''){
errorMsg[2].innerHTML = 'Vous devez entrer une address mail';
failureIcon[2].style.opacity = "1";
isFormValid = false;
} else {
errorMsg[2].innerHTML = '';
failureIcon[2].style.opacity = "0";
successIcon[2].style.opacity = "1";
isFormValid = true;
}
// Validate birthday
if(birthdate.value === ''){
errorMsg[3].innerHTML = 'Vous devez entrer une date de naissance';
isFormValid = false;
} else {
errorMsg[3].innerHTML = '';
successIcon[3].style.opacity = "1";
isFormValid = true;
}
// Validate quantity
if(quantity.value === ''){
errorMsg[4].innerHTML = 'Ce champ ne peut pas être vide';
failureIcon[4].style.opacity = "1";
isFormValid = false;
} else {
errorMsg[4].innerHTML = '';
failureIcon[4].style.opacity = "0";
successIcon[4].style.opacity = "1";
isFormValid = true;
}
// Validate location
for (i=0; i<city.length; i++) {
if(city[i].checked==true){
errorMsg[5].innerHTML = '';
isFormValid = true;
break;
}
else {
errorMsg[5].innerHTML = "Vous devez choisir une option";
isFormValid = false
// return false;
}
}
// Validate checkbox
if(checkbox1.checked) {
errorMsg[6].innerHTML = '';
isFormValid = true;
} else {
errorMsg[6].innerHTML = "Vous devez accepter les conditions d'utilisation";
isFormValid = false
}
}