首页 > 解决方案 > 输入空时jQuery文本输入实时验证清除错误

问题描述

我从网上获取了一些代码来验证名字。它可以工作,但是我想进行一些调整。我希望该字段为空时错误消息消失。此外,我想为文本添加边距,因为它与下一个字段不均匀,但似乎无法使其工作。

这是 Javascript 的标记。这使用引导程序和下面包含的另一个样式表。

$(document).ready(function () {
  var $regexname = /^([a-zA-Z]{2,16})$/;
  $('.name').on('keypress keydown keyup', function () {
    if (!$(this).val().match($regexname)) {
      // there is a mismatch, hence show the error message
      $('.emsg').removeClass('hidden');
    } else {
      // else, do not display message
      $('.emsg').addClass('hidden');
    }
  });
});
.signup2container-stage1 {
  width: 88%;
  margin: auto;
}

#signupsectioncontainer-stage2 {
  float: left;
  width: 45%;
  height: 2000px;
  background-color: orange;
  margin-top: 20px;
}

#signupsectioncontainer-stage3 {
  width: 80%;
  height: 90%;
  background-color: #ffffff;
  margin: auto;
}

#signup2validationinputs input {
  width: 100%;
  height: 45px;
  margin: 10px 0px 10px 0px;
}

.signuptextinputsstyle1 {
  outline-width: 0;
  background-color: #e3e5e8;
  border: none;
  padding: 10px 10px 10px 10px;
  float: left;
  display: block;
}

#signup2submitbutton {
  width: 100%;
  margin-top: 10px;
  padding: 20px 10px 20px 10px;
  border: none;
  outline-width: 0;
  color: #ffffff;
  background-color: #4caf50;
}

#signup2submitbutton #signup2submitbutton:hover {
  background-color: #48a44d;
}

.emsg {
  color: red;
}

.hidden {
  visibility: hidden;
}
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="clear">
</div>
<div class="signup2container-stage1">
  <div id="signupsectioncontainer-stage2">
    <h1 id="signup2title">Sign Up</h1>
    <div id="signupsectioncontainer-stage3">
      <div id="signup2validationinputs">
        <input class="name signuptextinputsstyle1" type="text" placeholder="First Name" required/>
        <p>
          <span id="validname" class="emsg hidden">Please Enter a Valid Name</span>
        </p>
        <input class="signuptextinputsstyle1" type="text" name="" placeholder="Last Name">
        <input class="signuptextinputsstyle1" type="text" name="" placeholder="Choose a Username">
        <input class="signuptextinputsstyle1" type="text" name="" placeholder="Date Of Birth">
        <input class="signuptextinputsstyle1" type="text" name="" placeholder="Email">
        <input class="signuptextinputsstyle1" type="password" name="" placeholder="Create Password">
        <input class="signuptextinputsstyle1" type="password" name="" placeholder="Confirm Password">
        <button id="signup2submitbutton">SIGN UP</button>
      </div>
    </div>
  </div>
</div>
在此先感谢您的帮助,并为混乱的代码道歉。

标签: jqueryhtmlcss

解决方案


使用 jquery .change 函数并检查值是否为空。

$(".name").change(function {
     if (!$this.val()) {
         $(".emsg").addClass("hidden")
    }
})

希望这可以帮助。


推荐阅读