这个Javascript代码如何更好地处理if / else语句,或者可能使用switch?

时间:2018-04-05 04:40:27

标签: javascript html5 forms input submit

首先,如果这违反了规则,或者对此感到不满,我非常抱歉并且可以随意关闭/关闭。我拼命地卡住了。

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

以下是一些指导原则......

验证四个单独的表单:

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

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

代码看起来对我来说是正确的,而且是自发的,但我相信,因为javascript一次只能查看一行,所以它不能正确显示错误消息,甚至根本无法访问代码的某些部分。< / p>

这是我的大量javascript代码,我主要是想找到一种方法来突破我的代码似乎陷入的if / else块:

&#13;
&#13;
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;
  }
}
&#13;
<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>
&#13;
&#13;
&#13;

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

1 个答案:

答案 0 :(得分:0)

我会将所有输入放入对象中,这样就可以自动遍历对象。

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