使用JavaScript验证HTML表单

时间:2019-02-26 13:03:09

标签: javascript html

我刚接触JavaScript和HTML。我正在尝试使用JavaScript验证反馈HTML表单。尽管如果输入框为空,代码应显示警报,但不会显示警报。我已经研究了这个问题并修改了我的代码,但是这些似乎都没有起作用。

JavaScript代码:

function validateForm() {
  var firstName = document.forms['feedback']['firstName'].value;
  if (firstName == null || firstName == "") {
    alert("First name is required");
    return false;
  }
  var lastName = document.forms['feedback']['lastName'].value;
  if (lastName == null || lastName == "") {
    alert("Surname is required");
    return false;
  }
  var email = document.forms['feedback']['email'].value;
  if (email == null || email == "") {
    alert("Email address is required");
    return false;
  }
  var date = document.forms['feedback']['date'].value;
  if (date == null || date == "") {
    alert("Date accessed is required");
    return false;
  }
  var tips = document.forms['feedback']['tips'].value;
  if (tips == null || tips == "") {
    alert("Web design tips is required");
    return false;
  }
  return true;
}

HTML代码:

<form name="feedback" onsubmit="return validateForm">
  First name: <input type="text" name="firstName" id="firstName">
  <br /> Surname: <input type="text" name="lastName" id="lastName">
  <br /> Email address: <input type="text" name="email" id="email">
  <br /> Date accessed: <input type="date" name="date" id="date">
  <br /> Web design tips: <textarea name="tips" id="tips"></textarea>
  <br />
  <button>Submit</button>
</form>

谢谢!

1 个答案:

答案 0 :(得分:2)

您实际上并没有在调用函数,应该具有 return validateForm(); 来调用它:

function validateForm() {
  var firstName = document.forms['feedback']['firstName'].value;
  if (firstName == null || firstName == "") {
    alert("First name is required");
    return false;
  }
  var lastName = document.forms['feedback']['lastName'].value;
  if (lastName == null || lastName == "") {
    alert("Surname is required");
    return false;
  }
  var email = document.forms['feedback']['email'].value;
  if (email == null || email == "") {
    alert("Email address is required");
    return false;
  }
  var date = document.forms['feedback']['date'].value;
  if (date == null || date == "") {
    alert("Date accessed is required");
    return false;
  }
  var tips = document.forms['feedback']['tips'].value;
  if (tips == null || tips == "") {
    alert("Web design tips is required");
    return false;
  }
  return true;
}
<form name="feedback" onsubmit="return validateForm();">
  First name: <input type="text" name="firstName" id="firstName">
  <br /> Surname: <input type="text" name="lastName" id="lastName">
  <br /> Email address: <input type="text" name="email" id="email">
  <br /> Date accessed: <input type="date" name="date" id="date">
  <br /> Web design tips: <textarea name="tips" id="tips"></textarea>
  <br />
  <button>Submit</button>
</form>