提交时验证表单

Validate form on submit

我已经创建了五个输入字段和一个提交按钮来验证这些字段,但不知何故在提交时未对其进行验证。
在我的 JS 中,我动态打印错误。我通过代码调试得到了正确的值和错误,但它没有动态显示。

function seterror(id, error) {
  // set error
  var element = document.getElementById(id);
  debugger;
  console.log(element);
  element.getElementsByClassName('ferror')[0].innerHTML = error;
}

function validateForm(e) {
  e.preventDefault();
  var returnval = true;

  var name = document.forms['myForm']['fname'].value;
  if (name.length < 5) {
    seterror("uname", "abc");
    returnval = false;
  }

  return returnval;
}
.ferror {
  color: red;
}
<h1>Form Validation Demo</h1>
<form onsubmit="return validateForm()" name="myForm">

  Name*: <input type="text" id="uname" name="fname"><b><span class="ferror"></span></b><br> Password*: <input type="password" id="pass" name="fpass"><b><span class="ferror"></span></b><br> Confirm Password*: <input type="password" id="cpassword" name="fcpass"><b><span class="ferror"></span></b>  <br> Email*: <input type="email" id="uemail" name="femail"><b><span class="ferror"></span></b> <br> Phone*:
  <input type="phone" id="uphone" name="fphone"><b><span class="ferror"></span></b> <br>
  <input type="submit" class="btn" value="submit">

</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

考虑到问题下的所有评论,以下是我对更灵活的重制的建议:

  • 不要为您的字段使用 ID
  • 使用额外的 <label> 作为包装器
  • 不要用无用的空 <span> 错误元素膨胀 HTML - 使用 JS 创建它们
  • 使用适当的addEventListener()并在验证函数中使用其事件
  • 使用一个errors数组来存储验证每个部分的所有错误
  • 仅在最后,如果 errors 数组中有项目(意味着某些内容无效)- 在这种情况下使用 Event.preventDefault() 来阻止提交表单。

// Utility functions:
const EL = (sel, parent) => (parent || document).querySelector(sel);
const ELS = (sel, parent) => (parent || document).querySelectorAll(sel);
const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);


// Form validation script:
const EL_form = EL("#myForm");

const validateForm = (evt) => {

  // Remove old errors
  ELS(".ferror", EL_form).forEach(el => el.remove());

  // Prepare an array to hold your errors
  const errors = [];

  // Get the desired fields:
  
  const EL_fname = EL('[name="fname"]', EL_form);
  const EL_fpass = EL('[name="fpass"]', EL_form);
  const EL_fcpass = EL('[name="fcpass"]', EL_form);
  const EL_femail = EL('[name="femail"]', EL_form);
  const EL_fphone = EL('[name="fphone"]', EL_form);

  // Validation and errors:
  
  if (EL_fname.value.trim().length <= 4) {
    errors.push({name: "fname", text: "Name is too short (min 4 chars)"});
  }
  
  if (EL_fpass.value.trim().length <= 8) {
    errors.push({name: "fpass", text: "Password is too short (min 8 chars)"});
  }
  
  if (EL_fpass.value !== EL_fcpass.value) {
    errors.push({name: "fcpass", text: "Passwords do not match"});
  }
  
  if (!/^.+@.+\./.test(EL_femail.value)) {
    errors.push({name: "femail", text: "Invalid Email address"});
  }
  
  if (EL_fphone.value.trim().replace(/\D/g, "").length <= 6) {
    errors.push({name: "fphone", text: "Invalid telephone number"});
  }
  
  // Show errors:
  errors.forEach(err => {
    const EL_error = ELNew("span", {
      className: "ferror",
      textContent: err.text,
    });
    EL(`[name="${err.name}"]`, EL_form).closest("label").append(EL_error);
  });
  
  // Prevent Form subnit on any error
  if (errors.length) {
    evt.preventDefault();
  }
  
};

EL_form.addEventListener("submit", validateForm);
form label {
  display: block;
}
.ferror {
  color: red;
  font-weight: 700;
}
<form id="myForm">

  <label>Name: <input name="fname" type="text"></label>
  <label>Password: <input name="fpass" type="password"></label>
  <label>Confirm Password: <input name="fcpass" type="password"></label>
  <label>Email: <input name="femail" type="email"></label>
  <label>Phone: <input name="fphone" type="phone"></label>
  <br>
  <input type="submit" class="btn" value="Submit">
  
</form>