Bootstrap 4表单验证-调用checkValidity()后自定义样式不起作用

时间:2019-01-28 00:27:02

标签: html5 validation bootstrap-4

form标记指定 class =“ needs-validation” ,并具有 novalidate 属性以指示自定义验证。

在代码运行并显示表单时,单击带有空白文本字段的按钮,由于这是必需的,因此它应该显示消息并将字段设置为红色。

通过调用 checkValidity()进行验证,并且对于空字段返回false,但是该字段的样式既不是:invalid 也不是 :有效

这是有关我正在尝试的文档:https://getbootstrap.com/docs/4.0/components/forms/#validation

谢谢

$(function () {
    $("#btnSubmit").on("click", function (e) {
        var form = $("#CertForm")[0];
        var isValid = form.checkValidity();
        if (!isValid) {
            e.preventDefault();
            e.stopPropagation();
        }
        form.classList.add('was-validated');
        return false; // For testing only to stay on this page
    });
});
<link href="https://ajax.aspnetcdn.com/ajax/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/4.2.1/bootstrap.min.js"></script>
<!-- 
  Why neither feedback displays when clicking Submit?
  Also, the required txtName input field should be red if invalid
-->

<form id="CertForm" class="needs-validation" novalidate="">
    <label for="txtName"> * Name:</label>
    <input id="txtName" required /> Blank for Invalid case
    <div class="invalid-feedback">Please enter a name</div>
    <div class="valid-feedback">Looks good!</div>
    <br />
    <button id="btnSubmit" type="submit" class="btn btn-primary">Click Me!</button>
</form>

1 个答案:

答案 0 :(得分:1)

您为输入元素错过了form-control类。如引导程序所说:

  

文本表单控件(如s,s和s)是   .form-control类的样式。包括常规样式   外观,焦点状态,大小等。

顺便说一句,您还没有设置输入类型,例如“文本”。

工作代码:

$(function () {
    $("#btnSubmit").on("click", function (e) {
        var form = $("#CertForm")[0];
        var isValid = form.checkValidity();
        if (!isValid) {
            e.preventDefault();
            e.stopPropagation();
        }
        form.classList.add('was-validated');
        return false; // For testing only to stay on this page
    });
});
<link href="https://ajax.aspnetcdn.com/ajax/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/4.2.1/bootstrap.min.js"></script>
<!-- 
  Why neither feedback displays when clicking Submit?
  Also, the required txtName input field should be red if invalid
-->

<form id="CertForm" class="needs-validation" novalidate="">
    <label for="txtName"> * Name:</label>
    <input id="txtName" class="form-control" type="text" required /> Blank for Invalid case
    <div class="invalid-feedback">Please enter a name</div>
    <div class="valid-feedback">Looks good!</div>
    <br />
    <button id="btnSubmit" type="submit" class="btn btn-primary">Click Me!</button>
</form>