如何验证javascript中的空字段并传递错误消息以警告bootstrap

时间:2016-09-28 03:21:25

标签: javascript jquery twitter-bootstrap alert

我想通过使用javascript验证字段并将错误消息传递给引导程序警报。我怎样才能做到这一点?有人可以帮忙吗?这是我的javascript函数:

function validateValues() {
    var f = document.frm;

    if (f.UsrID.value == "") {
        alert('Please fill in User ID'); < --How to pass this error message to Bootstrap alert ?
            f.UsrID.focus();
        return false;
    }
}

这是我想要显示错误消息的地方

<div class="alert alert-danger fade in">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span></button>
    <strong>Error message:</strong>
</div>

2 个答案:

答案 0 :(得分:1)

单独的Bootstrap可以在没有任何添加脚本的情况下验证您的表单:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

  <form data-toggle="validator" role="form">
  <div class="form-group">
    <label for="inputEmail" class="control-label">Email</label>
    <input type="email" class="form-control" id="inputEmail" placeholder="Email" data-error="Bruh, that email address is invalid" required>
    <div class="help-block with-errors"></div>
  </div>
  <div class="form-group">
    <button type="submit" class="btn btn-primary">Submit</button>
  </div>
</form>

希望这有帮助

答案 1 :(得分:0)

<div class="alert alert-danger fade in" id="putinhere">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span></button>
    <strong>Error message:</strong>
</div>

function validateValues() {
var f = document.frm,
    x = document.getElementById('putinhere');

if (f.UsrID.value=="") {
    x.children[2].innerHTML += ' Please fill in User ID.';
    f.UsrID.focus();
    return false;
  }
}

我在你的div上放了一个ID,这样我就可以更容易地获得/引用它了。 #EZ4rtz