【问题标题】:e.preventDefault() not letting me submit my forme.preventDefault() 不让我提交表单
【发布时间】:2020-04-08 00:53:05
【问题描述】:

我编写了一些 Javascript 来验证表单。但是,如果表单字段通过所有验证,则表单永远不会提交!我的代码是否以某种方式错误地阻止了表单提交?如果我删除所有 Javascript 并使用浏览器的内置验证,则表单执行正常并将用户添加到数据库中。

const form = document.getElementById('form');

const first_name = document.getElementById('first_name');
const last_name = document.getElementById('last_name');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');

// Show input error message
function showError(input, message) {
    input.className = 'form-control is-invalid';
    const small = input.parentElement.querySelector('small');
    small.className = 'invalid-feedback';
    small.innerText = message;
}

// Show success outline
function showSuccess(input, message) {
    input.className = 'form-control is-valid';
    const small = input.parentElement.querySelector('small');
    small.className = 'valid-feedback';
    small.innerText = message;
}


function checkRequired(inputArray) {
    inputArray.forEach(function(input) {
      if (input.value.trim() === '') {
        showError(input, `${getFieldName(input)} is required`);
        return false;
      } else {
        showSuccess(input, "Looks Good!");
        return true;
      }
    });
}

// Check email is valid
function checkEmail(input) {
  const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  if (re.test(input.value.trim())) {
    showSuccess(input, 'Looks Good!');
    return true;
  } else {
    showError(input, 'Email is not valid');
    return false;
  }
}

// Check input length
function checkLength(input, min, max) {
  if (input.value.length < min) {
    showError(
      input,
      `${getFieldName(input)} must be at least ${min} characters`
    );
    return false;
  } else if (input.value.length > max) {
    showError(
      input,
      `${getFieldName(input)} must be less than ${max} characters`
    );
    return false;
  } else {
    showSuccess(input, 'Looks Good!');
    return true;
  }
}

// Check passwords match
function checkPasswordsMatch(input1, input2) {
  if (input1.value !== input2.value) {
    showError(input2, 'Passwords do not match');
    return false;
  }
  return true;
}

// Get fieldname
function getFieldName(input) {
  return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}

// Event listeners
form.addEventListener('submit', function(e) {

  if (!checkRequired([first_name, last_name, username, email, password, password2])) {
      e.preventDefault();
  }
  if (!checkLength(username, 3, 15)) {
      e.preventDefault();
  }
  if (!checkLength(password, 6, 25)) {
      e.preventDefault();
  }
  if (!checkEmail(email)) {
      e.preventDefault();
  }
  if (!checkPasswordsMatch(password, password2)) {
      e.preventDefault();
  }
});

【问题讨论】:

    标签: javascript dom-events addeventlistener preventdefault


    【解决方案1】:

    您的 checkRequired 函数目前永远不会返回任何内容:

    function checkRequired(inputArray) {
        inputArray.forEach(function (input) {
            if (input.value.trim() === '') {
                showError(input, `${getFieldName(input)} is required`);
                return false;
            } else {
                showSuccess(input, "Looks Good!");
                return true;
            }
        });
    }
    

    你在回调内部返回,但回调忽略了它的返回值(你仍然不想在循环内返回true,你只想在所有迭代完成后返回true )

    要查找第一个无效输入,请使用.find

    function checkRequired(inputArray) {
      const invalidInput = inputArray.find(input => input.value.trim() === '');
      if (invalidInput) {
        showError(input, `${getFieldName(invalidInput)} is required`);
        return false;
      }
      return true;
    }
    

    如果您想为每个无效输入调用showError,那么:

    function checkRequired(inputArray) {
      let valid = true;
      for (const input of inputArray) {
        if (input.value.trim() === '') {
          valid = false;
          showError(input, `${getFieldName(input)} is required`);
        }
      }
      return valid;
    }
    

    【讨论】:

    • 谢谢!我将 show success 作为 else 添加到循环中,并将 checkRequired 函数移到最后一个以在 addEventListener 中执行以获取我正在寻找的行为。
    • 函数 checkRequired(inputArray) { 让有效 = true; for (const input of inputArray) { if (input.value.trim() === '') { valid = false;显示错误(输入,${getFieldName(input)} is required); } else { showSuccess(input, '看起来不错!'); } } 返回有效; }
    【解决方案2】:

    你没有从checkRequired 返回任何东西,所以它的值将永远是false。虽然应该没有性能问题,但最好使用for 循环,以便尽早中断。

    function checkRequired(inputArray) {
        for (let input of inputArray) {
            if (input.value.trim() === '') {
                showError(input, `${getFieldName(input)} is required`);
                return false;
            }
        }
    
        return true;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-19
      • 1970-01-01
      • 2021-09-26
      相关资源
      最近更新 更多