如何为每个空表单字段生成错误消息

f0brbegy  于 2021-09-23  发布在  Java
关注(0)|答案(5)|浏览(199)

我试图为每个空字段显示一条错误消息,我的问题是当我提交带有空字段(一个或两个)的表单时,所有错误消息都会出现。我希望每个空字段只显示一条错误消息,而不是全部。
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);
8wigbo56

8wigbo561#

您可以使用类作为输入,并跟踪 isValid 形式的布尔值。您正在使用代码设置所有错误字段。在这里,我们可以使用 closest() 寻找包容 label 那么 querySelector 查找错误字段的步骤

el.closest('label').querySelector('.error-field');
const submitButton = document.querySelector('.form-button');
const validate = (e) => {
  e.preventDefault();
  let isValid = true
  document.querySelectorAll('.validate').forEach(el => {
    let error = el.closest('label').querySelector('.error-field').classList;
    if (el.value.trim().length === 0) {
      isValid = false;
      error.add('error-active');
      el.classList.add('invalid')
    } else {
      error.remove('error-active');
      el.classList.remove('invalid')
    }
  })
  return isValid;
}

submitButton.addEventListener('click', validate);
.error-field.error-active,
input.invalid{
  color: #f00;
}
<form action="" id="my-form">
  <label for="name">
        <input type="text" id="name" class='validate' 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" class='validate' name="lastName" placeholder="Last Name">
        <p class="error-field">Last Name cannot be empty</p>
      </label>
  <label for="email">
        <input type="email" id="email" class='validate' 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" class='validate' 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>
mspsb9vt

mspsb9vt2#

这是因为在每个if语句中,您循环遍历表单中的所有错误字段,并将其全部更新。因此,您可以做的是,首先为html文件中的每个dom条目添加唯一id,例如err password、error name等,然后在每个if语句中获取需要显示错误的相关eror字段,并仅更新该字段。

c6ubokkw

c6ubokkw3#

使用nextelementsibling将大大简化您的代码。。。因为错误消息总是在 input .
在显示或不显示错误的条件下。。这就是问题所在 value.length 你必须检查一下。

const submitButton = document.querySelector('.form-button');
const errorField = document.querySelectorAll(".error-field");

const validate = (e) => {

  // Remove any already displayed error
  errorField.forEach(function(error){
    error.classList.remove("invalid");
  })

  // Loop through all inputs to check the value length
  document.querySelectorAll("form input").forEach(function(input){
    if(input.value.length < 1){
      input.nextElementSibling.classList.toggle("invalid");
    }
  })

  // Prevent submit only if there are errors shown
  let errorCount = document.querySelectorAll(".error-field.invalid").length
  if(errorCount){
    e.preventDefault();
  }
}

submitButton.addEventListener('click' , validate);
label{
  display: block;
}

label p{
  margin: 0;
}

.error-field{
  display: none;
  color: red;
}

.invalid{
  display: inline-block;
}
<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>
4uqofj5v

4uqofj5v4#

希望这能解决你的问题。注意,password改为passwordd,您访问所有错误字段时没有指定哪个字段

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 passwordD = document.getElementById("password");

  if (firstName.value < 1) {
    errorField[0].classList.toggle('error-active');
    errorField[0].style.color = "red";
    firstName.classList.toggle("invalid");

  }

  if (lastName.value < 1) {
    errorField[1].classList.toggle("error-active");
    errorField[1].style.color = "red";
    lastName.classList.toggle("invalid");

  }

  if (email.value < 1) {
    errorField[2].classList.toggle("error-active");
    errorField[2].style.color = "red";
    email.classList.toggle("invalid");

  }

  if (password.value < 1) {
    errorField[3].classList.add("error-active");
    errorField[3].style.color = "red";
    passwordD.classList.toggle("invalid");

  } else {
    passwordD.classList.remove("invalid");

    errorField.forEach((f) => {
      f.classList.remove("error-active");
      f.style.color = "black";
    });
    return true;
  }

  return false;
}

submitButton.addEventListener('click', validate);
<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>
sshcrbum

sshcrbum5#

我建议您使用一个表单验证js插件,而不是重新发明轮子,例如表单验证插件

相关问题