【问题标题】:How can I exclude required fields in a validation script? [duplicate]如何在验证脚本中排除必填字段? [复制]
【发布时间】:2021-10-14 18:54:21
【问题描述】:

我正在尝试创建一个基于必填字段进行验证的多步骤表单。 我正在使用的当前 Javascript 只是查找填写的字段以验证表单。但是如何让它忽略 html 中未标记为“必填”的字段?

谢谢!

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;
    }
  }
  // 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
}

【问题讨论】:

  • 你会用那些单字母的变量名树敌。只是不要。

标签: javascript forms


【解决方案1】:

但是如何让它忽略 html 中未标记为“必填”的字段?

以下解决方案检查input 元素中的required 属性。所以在for循环中,你要做的第一件事是if(!y[i].required){ continue; },换句话说,如果y[i].requiredundefined,那么continue(或者跳过这个迭代)。

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 y[i].required is undefined... skip to the next <--
    if(!y[i].required){ continue; }
    // 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;
    }
  }
  // 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
}

【讨论】:

  • 请编辑您的答案并添加一些文本来解释您在 OP 的代码中发现了哪些问题以及您的答案如何修复或解决这些问题。
  • 这成功了!谢谢!!我只是不知道如何调用所需的属性,因为它不是一个类。所以它被认为是一个标签?
  • @JeepGirl - 它被认为是标签/元素的属性
  • 如果提供的解决方案符合您的要求,请记得将其标记为已接受的答案。
猜你喜欢
  • 1970-01-01
  • 2015-01-15
  • 1970-01-01
  • 2012-05-23
  • 2013-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多