【问题标题】:How can this Javascript code handle the if/else statements better, or possibly use switches?这个 Javascript 代码如何更好地处理 if/else 语句,或者可能使用开关?
【发布时间】:2018-09-14 19:10:00
【问题描述】:

首先,如果这违反了规则,或者不满意,我很抱歉,请随意投反对票/关闭。我被卡住了。

我编写的 HTML 页面遇到了问题,该页面应该由具有特定要求的输入组成,添加 div 以显示错误消息,并自动更新这些错误消息 onblur。这项任务是为了测试我们的 javascript 技能,因此必须通过 javascript 进行完全验证。

这里有一些指导方针...

为四个不同的事情验证表单:

  • 存在必填字段
  • 密码字段相等
  • 遵守密码策略(一个大写,一个数字,长度 > 7)
  • 电子邮件地址的有效性

当其中任何一个被违反时,我应该停用表单的提交按钮,使其不可点击,并在错误显示中添加一个子“div”,其中包含描述情况的错误消息。

代码对我来说似乎是正确的,并且可以自发运行,但我相信由于一次只查看一行 javascript,它无法正确显示错误消息,甚至根本无法访问我的代码的某些部分。

这是我的一大段 javascript 代码,我主要是在寻找一种方法来打破我的代码似乎卡在的这些 if/else 块:

function formValidation() {

  var form = document.getElementById('project-form');
  var username = document.getElementById('username');
  var name = document.getElementById('name');
  var phone = document.getElementById('phone-number');
  var email = document.getElementById('email');
  var password = document.getElementById('password');
  var passwordConfirmation = document.getElementById('password-confirmation');
  var submit = document.getElementById('submit-btn');
  var errorDisplay = document.getElementById('error-display');
  var missingFieldBoolean = false;
  var passwordMismatchBoolean = false;
  var isUpper = false;
  var isNumber = false;
  var passwordLength = false;
  var validEmail = false;
  var createDiv = document.createElement("DIV");
  var passwordConstraint, passwordConstraintError;
  var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

  //Checks all fields for empty values and updates error div

  if (username.value.length == 0 || name.value.length == 0 || email.value.length == 0 || password.value.length == 0 || passwordConfirmation.value.length == 0) {

    missingField = errorDisplay.appendChild(createDiv);

    missingField.setAttribute("id", "required-field-error");

    missingFieldError = document.getElementById('required-field-error');

    missingFieldError.innerHTML = "Missing Fields: ";

    if (username.value.length == 0) {
      missingFieldError.innerHTML += "Username - ";
    }
    if (name.value.length == 0) {
      missingFieldError.innerHTML += "Full Name - ";
    }
    if (email.value.length == 0) {
      missingFieldError.innerHTML += "Email - ";
    }
    if (password.value.length == 0) {
      missingFieldError.innerHTML += "Password - ";
    }
    if (passwordConfirmation.value.length == 0) {
      missingFieldError.innerHTML += "Password Confirmation - ";
    }
  } else {
    errorDisplay.removeChild(missingFieldError);
    missingFieldBoolean = true;
  }

  //Checks password vs password confirmation to see if they match, else updates error div

  if (password.value != passwordConfirmation.value) {
    passwordMismatch = errorDisplay.appendChild(createDiv);

    passwordMismatch.setAttribute("id", "password-mismatch-error");

    passwordMismatchError = document.getElementById('password-mismatch-error');

    passwordMismatchError.innerHTML = "The Password and Password Confirmation do not match. Please re-enter.";
  } else {
    errorDisplay.removeChild(passwordMismatchError);
    passwordMismatchBoolean = true;
  }

  //for loop to iterate through password to check for required characters, else updates error div

  for (var index = 0; index < password.value.length; index++) {
    if (password.value.charAt(index) == password.value.charAt(index).toUpperCase) {
      isUpper = true;
    }
    if ("0123456789".indexOf(password.value.charAt(index)) > -1) {
      isNumber = true;
    }
    if (password.value.length > 7) {
      passwordLength = true;
    } else {
      passwordConstraint = errorDisplay.appendChild(createDiv);

      passwordConstraint.setAttribute("id", "password-constraint-error");

      passwordConstraintError = document.getElementById('password-constraint-error');

      passwordConstraintError.innerHTML = "The Password must be 8 characters long, with one uppercase letter and one number. ";
    }
  }

  //checks if password constraints are met and removes div if true

  if (isUpper && isNumber && passwordLength) {
    errorDisplay.removeChild(passwordConstraintError);
  }

  //checks email, if invalid it adds error div, else it removes the div   ***NOT WORKING***

  if (!(mailformat.test(email.value))) {
    invalidEmail = errorDisplay.appendChild(createDiv);

    invalidEmail.setAttribute("id", "invalid-email-error");

    invalidEmailError = document.getElementById('invalid-email-error');

    invalidEmailError.innerHTML = "Please enter a valid email address.";
  } else {
    errorDisplay.removeChild(invalidEmailError);
    validEmail = true;
  }

  //if all requirements are met and true, submit button becomes enabled  ***NOT WORKING***

  if (isUpper && isNumber && passwordLength && missingFieldBoolean && passwordMismatchBoolean && validEmail) {

    submit.disabled = false;
  }
}
<div id="error-display"></div>

<br>
<form id="project-form" action="/submit.php" method="get" onclick="formValidation()">

  <label>Username:</label>

  <input id="username" type="text" onblur="formValidation()" required>
  <c>*</c>

  <br>
  <label>Full Name:</label>

  <input id="name" type="text" onblur="formValidation()" required>
  <c>*</c>

  <br>
  <label>Phone Number:</label>

  <input id="phone-number" type="tel">

  <br>
  <label>Email:</label>

  <input id="email" type="email" onblur="formValidation()" required>
  <c>*</c>

  <br>
  <label>Password:</label>

  <input id="password" type="password" required onblur="formValidation()">
  <c>*</c>

  <br>
  <label>Confirm Password:</label>

  <input id="password-confirmation" type="password" required onblur="formValidation()">
  <c>*</c>
  <br>
  <br>
  <input id="submit-btn" type="submit" value="Submit" disabled>
</form>

非常感谢,如果我违反了规则,再次抱歉。

【问题讨论】:

  • 你有很多未声明的变量要开始,除非它们是全局声明的并且你没有在这里包含它们。它导致了很多错误。你知道如何在浏览器中使用调试器吗?
  • 是的,至少相当不错。当我尝试删除子 div 时,我看到它正在破坏许多 else 块。我注意到我没有声明一些与删除和添加错误 div 相关的变量。我将在声明其余变量的地方声明它们。

标签: javascript html forms input submit


【解决方案1】:

我会将所有输入放入一个对象中,这样您就可以自动迭代该对象。

const fieldValues = [
  'username',
  'name',
  'phone-number',
  'email',
  'password',
  'password-confirmation',
]
.reduce((fieldsSoFar, fieldName) => {
  fieldsSoFar[fieldName] = document.getElementById(fieldName).value;
  return fieldsSoFar;
}, {});

const missingFieldsStr =
  Object.entries(fieldValues)
  .filter(([, fieldValue]) => fieldValue.length === 0)
  .map(([fieldName]) => {
    const words = fieldName.split(' ');
    const upperWords = words.map(word => word.slice(0, 1).toUpperCase() + word.slice(1))
    return upperWords;
  })
  .join(', ');
if (missingFieldsStr) {
  // display it
}

// skipping some lines...

const hasUpper = /[A-Z]/.test(fieldValues.password);
const hasNumber = /[0-9]/.test(fieldValues.password);

等等。

不要隐式创建全局变量 - 强烈考虑使用 linter。

仅当您有意使用或插入 HTML 标记(可能存在安全和编码问题)时才使用innerHTML。当您设置或检索文本值时,请改用textContent

【讨论】:

  • 感谢您的评论,我将不得不对此进行一些研究,因为我还没有深入了解 HTML/javascript。非常感谢,希望对我有帮助!
猜你喜欢
  • 1970-01-01
  • 2016-07-11
  • 2014-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多