Formvalidation中的JavaScript错误消息

时间:2018-08-23 13:30:44

标签: javascript forms validation error-messaging

我在删除表单验证中的自定义错误消息时遇到困难。每次我提交表单时,消息都会复制,并且我不知道如何在字段有效的情况下删除它们。我很高兴听到您的回答!

form.onsubmit = function valCheck(ev) {
  ev.preventDefault();

  var fields = ev.target
  console.log(fields);

  var nameVal = /^[a-zA-ZäÄüÜöÖáàiìíéèóòúù `´,.'-]+$/;
  var emailVal = /[^\s@]+@[^\s@]+\.[^\s@]+/;

  for (var i = 0; i < formLen; i++) {
    var errorText = document.createElement('P');
    div[i].appendChild(errorText);
    console.log(errorText);

    if (fields[i].value === "") {
        errorText.innerHTML = "This field should not be empty"
    }
    else if (fields[i].type == "text") {
      if (!fields[i].value.match(nameVal)) {
        errorText.innerHTML = "no numbers allowed"
      }
    }
    else if (fields[i].type == "email") {
      if (!fields[i].value.match(emailVal)) {
        errorText.innerHTML  = "insert a valid adress"
      }
    }
    else if (fields[i].type == "checkbox") {
      if (!fields[i].checked) {
        errorText.innerHTML = "checkbox need to be checked"
      }
    }
    else if (fields[i].type == "radio") {
      if (fields[i].checked) {
        errorText.innerHTML = "you need to select something"
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

我相信您可以在验证之前将空值分配给errorText.innerHTML

form.onsubmit = function valCheck(ev) {
  ev.preventDefault();

  errorText.innerHTML = '';

  // setting non-empty errorText.innerHTML if form is not valid
  // ...
}