我的表单验证错误消息消失了

时间:2020-03-13 13:35:39

标签: javascript html

我试图使用HTML,Bootstrap和JavaScript制作注册表。 当字段保留为空时,我能够收到错误消息,但是显示后该错误消息消失了。我不知道我在做什么错事

function checkValidation() {
    var firstName = document.getElementById('firstName').value;
    if (firstName == "") {
        console.log("enter");
        document.getElementById('firstNameErrorMessage').innerHTML = "please enter";
    } else {
        console.log("done");
    }
}
<div class="container-fluid">
  <div class="container">
    <h2>Registration Form</h2>
    <form class="form-horizontal" name="myForm">
      <div class="form-group">
        <label class="control-label col-sm-2" for="firstName">
        First Name
        </label>
        <div class="col-sm-10">
          <input type="text" name="firstName" class="form-control" id="firstName" placeholder="Enter your First Name" name="firstName">
          <div class="col-sm-12">
            <p id="firstNameErrorMessage"></p>
          </div>
        </div>
      </div>
      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
          <button type="submit" class="btn btn-default" onclick="checkValidation()">Submit</button>
        </div>
      </div>
    </form>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

您需要使用preventDefault才能使其按预期工作:

<div class="container-fluid">
<div class="container">
<h2>Registration Form</h2>
<form class="form-horizontal" name="myForm">
  <div class="form-group">
    <label class="control-label col-sm-2" for="firstName">
    First Name
    </label>
    <div class="col-sm-10">
      <input type="text" name="firstName" class="form-control" id="firstName" placeholder="Enter your First Name" name="firstName">
      <div class="col-sm-12">
        <p id="firstNameErrorMessage"></p>
      </div>
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="submit" class="btn btn-default" onclick="checkValidation(event)">Submit</button>
    </div>
  </div>
</form>

function checkValidation(e) {
e.preventDefault();
var firstName = document.getElementById('firstName').value;
if (firstName == "") {
    console.log("enter");
    document.getElementById('firstNameErrorMessage').innerHTML = "please enter";
} else {
    console.log("done");
  }
 }

在这里查看一些preventDefault问题:

How and when to use preventDefault()?

What's the difference between event.stopPropagation and event.preventDefault?