我试图为每个空字段显示一条错误消息,我的问题是当我提交带有空字段(一个或两个)的表单时,所有错误消息都会出现。我希望每个空字段只显示一条错误消息,而不是全部。
html:
<form action="" id="my-form">
<label for="name">
<input type="text" id="name" name="firstName" placeholder="First Name">
<p class="error-field">First Name cannot be empty</p>
</label>
<label for="last-name">
<input type="text" id="last-name" name="lastName" placeholder="Last Name">
<p class="error-field">Last Name cannot be empty</p>
</label>
<label for="email">
<input type="email" id="email" name="email" placeholder="Email Address">
<p class="error-field">Looks like this is not an email</p>
</label>
<label for="password">
<input type="password" id="password" name="password" placeholder="Password">
<p class="error-field">Password cannot be empty</p>
</label>
<button type="submit" name="submit" class="form-button">Claim your free trial </button>
<p>By clicking the button, you are agreeing to our <a href="" class="terms-conditions-link">Terms and Services</a></p>
</form>
javascript:
const submitButton = document.querySelector('.form-button');
const errorField = document.querySelectorAll(".error-field");
const validate = (e) => {
e.preventDefault();
const firstName = document.getElementById("name");
const lastName = document.getElementById("last-name");
const email = document.getElementById("email");
const password = document.getElementById("password");
if(firstName.value < 1 ) {
errorField.forEach((f) => f.classList.toggle('error-active'));
errorField.forEach((c) => c.style.color = "red");
firstName.classList.toggle("invalid");
return false;
}
if (lastName.value < 1) {
errorField.forEach((f) => f.classList.toggle("error-active"));
errorField.forEach((c) => (c.style.color = "red"));
lastName.classList.toggle("invalid");
return false;
}
if (email.value < 1) {
errorField.forEach((f) => f.classList.toggle("error-active"));
errorField.forEach((c) => (c.style.color = "red"));
email.classList.toggle("invalid");
return false;
}
if (password.value < 1) {
errorField.forEach((f) => f.classList.toggle("error-active"));
errorField.forEach((c) => (c.style.color = "red"));
password.classList.toggle("invalid");
return false;
} else {
password.classList.remove("invalid");
errorField.classList.remove("error-active");
}
return true;
}
submitButton.addEventListener('click' , validate);
5条答案
按热度按时间8wigbo561#
您可以使用类作为输入,并跟踪
isValid
形式的布尔值。您正在使用代码设置所有错误字段。在这里,我们可以使用closest()
寻找包容label
那么querySelector
查找错误字段的步骤mspsb9vt2#
这是因为在每个if语句中,您循环遍历表单中的所有错误字段,并将其全部更新。因此,您可以做的是,首先为html文件中的每个dom条目添加唯一id,例如err password、error name等,然后在每个if语句中获取需要显示错误的相关eror字段,并仅更新该字段。
c6ubokkw3#
使用nextelementsibling将大大简化您的代码。。。因为错误消息总是在
input
.在显示或不显示错误的条件下。。这就是问题所在
value.length
你必须检查一下。4uqofj5v4#
希望这能解决你的问题。注意,password改为passwordd,您访问所有错误字段时没有指定哪个字段
sshcrbum5#
我建议您使用一个表单验证js插件,而不是重新发明轮子,例如表单验证插件