无法在 Bootstrap 中进行验证

新手上路,请多包涵

我正在尝试 通过 Bootstrap 实现验证, 并在我的页面上粘贴了以下示例:

 <div class="form-group has-success">
  <label class="form-control-label" for="inputSuccess1">Input with success</label>
  <input type="text" class="form-control form-control-success" id="inputSuccess1">
  <div class="form-control-feedback">Success! You've done it.</div>
  <small class="form-text text-muted">Example help text that remains unchanged.</small>
</div>

我可以看到输入控件的外观发生了变化(现在它有点圆润并且更加美观) ,但 它仍然没有显示绿色边框,如链接到的页面上所示。我链接到的 Bootstrap 指出如下。

 <link rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" />

我试图用谷歌搜索这个问题,但无济于事。我有 一个说明这个问题的小提琴

我能做些什么呢?我错过了什么?

原文由 user1675891 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 623
1 个回答

引导程序 5(2021 年更新)

由于 Bootstrap 5 不再需要 jQuery,因此很容易使用 vanilla JavaScript 进行客户端验证。文档包括一个通用代码示例,该示例适用于所有带有 needs-validation 的表单。

 (function () {
    'use strict'

    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.querySelectorAll('.needs-validation')

    // Loop over them and prevent submission
    Array.prototype.slice.call(forms)
        .forEach(function (form) {
        form.addEventListener('submit', function (event) {
            if (!form.checkValidity()) {
            event.preventDefault()
            event.stopPropagation()
            }

            form.classList.add('was-validated')
        }, false)
        })
})()

Bootstrap 5 表单验证演示

Bootstrap 4(原始答案)

自 Bootstrap 4 beta 版本 起,验证已更改。

有效的状态选择器使用 was-validated 类,该类将在通过 客户端 JavaScript 验证表单后动态添加。例如…

 <form class="container was-validated" novalidate="">
    <div class="form-group">
        <label class="form-control-label" for="inputSuccess1">Input with success</label>
        <input type="text" class="form-control" name="i1" id="inputSuccess1">
        <div class="valid-feedback">Success! You've done it.</div>
    </div>
    <div class="form-group">
        <label class="form-control-label" for="inputSuccess2">Input with danger</label>
        <input type="text" class="form-control" name="i2" required="" id="inputSuccess2">
        <div class="invalid-feedback">That didn't work.</div>
    </div>
    <div class="">
        <button type="submit" class="btn btn-secondary">Text</button>
    </div>
</form>

https://codeply.com/go/45rU7UOhFo

表单验证示例演示 - Bootstrap 4.0.0


如文档中所述,如果您打算使用 服务器端 验证,您只需在表单控件上设置 is-validis-invalid 类…

 <form class="container">
    <div class="form-group">
        <label class="form-control-label" for="inputSuccess1">Input with success</label>
        <input type="text" class="form-control is-valid" id="inputSuccess1">
        <div class="valid-feedback">Success! You've done it.</div>
    </div>
</form>

原文由 Zim 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题