首页 > 解决方案 > 不要验证 javascript 中的隐藏字段

问题描述

你好,我是 javascript 和所有这些 html 和东西的新手。我有以下来自 w3schools 的代码来验证输入字段。我有这样的 html 输入字段。

<div id="employed" style="display:none;">
    <p><input placeholder="Name Of The Organization / Institution ..."  name="organization"></p>
    <p><input placeholder="Designation ..."  name="desig"></p>
    <p><input placeholder="Place Of Work  ..."  name="workplace"></p>
    <p><input placeholder="Communication Address ..."  name="cadd"></p>
    <p><input placeholder="E_mail ID ..."  name="offemail"></p>
    <p><input placeholder="Contact Number ..."  name="contact"></p>
  </div>  

当用户选择单选按钮时,我有一个显示隐藏字段的 javascript。但是,当我单击下一步时,即使字段被隐藏,它也会验证这些字段。用于验证的 javascript 是这样的。

function validateForm() {
  // This function deals with validation of the form fields
  var x, y, i, valid = true;
  x = document.getElementsByClassName("tab");
  y = x[currentTab].getElementsByTagName("input");
  // A loop that checks every input field in the current tab:
  for (i = 0; i < y.length; i++) {
    // If a field is empty...
    if (y[i].value == "") {
      // add an "invalid" class to the field:
      y[i].className += " invalid";
      // and set the current valid status to false
      //valid = false;
      (y[i].style.display == "none")?valid = true:valid = false;
    }
  }
  // If the valid status is true, mark the step as finished and valid:
  if (valid) {
    document.getElementsByClassName("step")[currentTab].className += " finish";
  }
  return valid; // return the valid status
}

请我现在正在学习,我被困在这里。提前致谢!

标签: javascripthtmlcss

解决方案


因为输入 dom 在您的文档中仍然可用,并且只是隐藏了。为了防止您的验证验证隐藏的输入。将您的代码更改为此。

function validateForm() {
  // This function deals with validation of the form fields
  var x, y, i, valid = true;
  x = document.getElementsByClassName("tab");
  y = x[currentTab].getElementsByTagName("input");
  // A loop that checks every input field in the current tab:
  for (i = 0; i < y.length; i++) {
    // If a field is empty...
    if (y[i].value == "" && y[i].parentElement.style.display != 'none') {
      // add an "invalid" class to the field:
      y[i].className += " invalid";
      // and set the current valid status to false
      //valid = false;
      (y[i].style.display == "none")?valid = true:valid = false;
    }
  }
  // If the valid status is true, mark the step as finished and valid:
  if (valid) {
    document.getElementsByClassName("step")[currentTab].className += " finish";
  }
  return valid; // return the valid status
}

推荐阅读