如何从有效控件中禁用Bootstrap 4验证样式

时间:2019-05-10 10:11:54

标签: javascript jquery html css bootstrap-4

我正在为我的应用程序使用bootstrap 4样式。应用程序有两个文本框和一个提交按钮。当您单击“保存”按钮时,它将调用Web API并异步获取一些详细信息(它不会重定向页面)。 验证仅适用于第一个文本框。

(function() {
  'use strict';
  window.addEventListener('load', function() {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();
<!DOCTYPE html>
<html>

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <title>Test Page</title>
</head>

<body>
  <form class="container needs-validation" novalidate>
    <div class="form-group row mt-5">
      <label for="txtSessionDescription" class="col-2 col-md-2 col-sm-2 col-form-label">Name</label>
      <div class="col-sm-10">
        <input type="tel" class="form-control" placeholder="Please enter your name" required />
        <div class="invalid-feedback">
          Please enter the name.
        </div>
      </div>
    </div>
    <div class="form-group row mt-5">
      <label for="txtSessionDescription" class="col-2 col-md-2 col-sm-2 col-form-label">Address:</label>
      <div class="col-sm-10">
        <input type="tel" class="form-control" />
      </div>
    </div>
    <div class="form-group row">
      <input type="submit" class="btn btn-primary" style="width: 100px;" value="Save" />
    </div>
  </form>
</body>

</html>

我的问题:

当我单击“保存”按钮而不在文本框中输入任何值时,绿色样式(验证为真样式)将应用于“地址”文本框。我不会那样做。

如果验证失败,我只需要应用红色样式(验证失败样式)。如果输入了值(验证为true),则不需要将任何样式应用于文本框。

此外,当我在“名称”文本框中输入一些值并单击“保存”按钮时,我也不想为该文本框设置绿色样式。

截屏:

Screenshot

8 个答案:

答案 0 :(得分:1)

我不喜欢覆盖CSS样式,因此您也可以选择仅指定要验证的字段,而不是整个表单。

将类添加到您的.form-group元素(例如.validate-me

    <form class="container needs-validation" novalidate>
        <div class="form-group row mt-5 validate-me">
            <label for="txtSessionDescription" class="col-2 col-md-2 col-sm-2 col-form-label">Name</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" placeholder="Please enter your name" required />
                <div class="invalid-feedback">
                    Please enter the name.
                </div>
            </div>
        </div>
        <div class="form-group row mt-5">
            <label for="txtSessionDescription" class="col-2 col-md-2 col-sm-2 col-form-label">Address:</label>
            <div class="col-sm-10">
                <input type="tel" class="form-control" formnovalidate="formnovalidate" id="address" />
            </div>
        </div>
        <div class="form-group row">
            <input type="submit" class="btn btn-primary" style="width: 100px;" value="Save"/>
        </div>
    </form>

现在稍微更改JavaScript,使用form-group类检索所有validate-me,而不是通过所有捕获的表单组调用form.classList.add('was-validated')循环并添加was-validated代替他们。

window.addEventListener('load', function () {
                // Fetch all the forms we want to apply custom Bootstrap validation styles to
                var forms = document.getElementsByClassName('needs-validation');

                // Get all form-groups in need of validation
                var validateGroup = document.getElementsByClassName('validate-me');

                // Loop over them and prevent submission
                var validation = Array.prototype.filter.call(forms, function (form) {
                    form.addEventListener('submit', function (event) {
                        if (form.checkValidity() === false) {
                            event.preventDefault();
                            event.stopPropagation();
                        }

                        //Added validation class to all form-groups in need of validation
                        for (var i = 0; i < validateGroup.length; i++) {
                            validateGroup[i].classList.add('was-validated');
                        }
                    }, false);
                });
            }, false);

答案 1 :(得分:1)

  (function () {
    'use strict';
    window.addEventListener('load', function () {
        const forms = document.getElementsByClassName('needs-validation');
        Array.prototype.filter.call(forms, function (form) {
            form.addEventListener('submit', function (event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                const invalidGroup = form.querySelectorAll(":invalid");
                for (let j = 0; j < invalidGroup.length; j++) {
                    invalidGroup[j].classList.add('is-invalid');
                }
            }, false);
        });
    }, false);
})();

答案 2 :(得分:0)

您可以覆盖is-valid验证的css。右键单击绿色复选框,然后选择检查,您可以看到哪个类导致了绿灯亮起

enter image description here 因此,您应该指定不继承自引导程序。代码应该是这样的:

<!DOCTYPE html>
<html>
<head>
  <style>
    .form-control.is-valid:focus, .was-validated :valid.form-control{ border-color:inherit !important;
    background-image: inherit !important;
    box-shadow:inherit !important;}

 </style>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>Test Page</title>
    <script type="text/javascript">
        (function () {
            'use strict';
            window.addEventListener('load', function () {
                // Fetch all the forms we want to apply custom Bootstrap validation styles to
                var forms = document.getElementsByClassName('needs-validation');
                // Loop over them and prevent submission
                var validation = Array.prototype.filter.call(forms, function (form) {
                    form.addEventListener('submit', function (event) {
                        if (form.checkValidity() === false) {
                            event.preventDefault();
                            event.stopPropagation();
                        }
                        form.classList.add('was-validated');
                    }, false);
                });
            }, false);
        })();
    </script>

</head>
<body>
    <form class="container needs-validation" novalidate id="myFrom" >
        <div class="form-group row mt-5">
            <label for="txtSessionDescription" class="col-2 col-md-2 col-sm-2 col-form-label">Name</label>
            <div class="col-sm-10">
                <input type="tel" class="form-control" placeholder="Please enter your name" required />
                <div class="invalid-feedback">
                    Please enter the name.
                </div>
            </div>
        </div>
        <div class="form-group row mt-5">
            <label for="txtSessionDescription" class="col-2 col-md-2 col-sm-2 col-form-label">Address:</label>
            <div class="col-sm-10">
                <input type="tel" class="form-control" />
            </div>
        </div>
        <div class="form-group row">
            <input type="submit" class="btn btn-primary" style="width: 100px;" value="Save"/>
        </div>
    </form>
</body>
</html>

我添加的是head标签下面的style标签和css选项。

答案 3 :(得分:0)

您可能想看看this answer

具体地说,不是将.was-validated添加到整个表单中,而是仅将.is-invalid添加到具有:invalid伪类的表单元素中。

此代码应适合您的情况:

for (var i = 0; i < validateGroup.length; i++) {
    var invalidGroup = validateGroup[i].querySelectorAll(":invalid");
    for (var j = 0; j < invalidGroup.length; j++) {
        invalidGroup[j].classList.add('is-invalid');
    }
}

答案 4 :(得分:0)

@Ilker Kadir Ozturk的帖子仅通过使用样式为我工作,除了我的有效字段边框是从我不想使用的先前颜色(黑色)继承的。我在剃须刀页面中使用Bootstrap 4和ASP.NET MVC。这是用我的颜色(#DDDDDD)调整的他的代码。我还在样式上方添加了评论:

 @*  This is to prevent the green color style on Bootstrap validation to be applied to all textboxes when the info is valid.
    Only the red color style(validation failed style) should be applied if the validation failed.
    If the values are ok, no styling should be applied to the text boxes.
    Also when the "submit" button is clicked, there is no need for the green color styling to show up either.
 *@

<style>
    .form-control.is-valid:focus, .was-validated :valid.form-control {
        border-color: #DDDDDD !important;
        background-image: inherit !important;
        box-shadow: inherit !important;
    }
</style>

答案 5 :(得分:0)

覆盖$form-validation-states scss变量。 Bootstrap 5中对此进行了记录,但是相同的技术也适用于版本4。

https://v5.getbootstrap.com/docs/5.0/forms/validation/#customizing

$form-validation-states: (
  "valid": (                               <-- delete this
    "color": $form-feedback-valid-color,
    "icon": $form-feedback-icon-valid
  ),
  "invalid": (
    "color": $form-feedback-invalid-color,
    "icon": $form-feedback-icon-invalid
  )
);

答案 6 :(得分:0)

在验证成功的情况下删除样式的部分解决方案

如果form.checkValidity()的评估为true,请从表单中删除was-validated类。


反应引导中的示例:

拥有<Form noValidate validated={this.state.validated} onSubmit={this.onSubmit}>

onSubmit = (e) => this.setState({ validated: !e.currentTarget.checkValidity()});

答案 7 :(得分:0)

这是我使用 jQuery 解决类似问题的方法:

在您的提交方法中,在调用 checkValidity() 后插入以下几行:

$("#myForm").find(":valid").parent().removeClass("was-validated"); // Optional: Removes all green borders that have been fixed since last submit attempt
$("#myForm").removeClass("needs-validation");
$("#myForm").find(":invalid").parent().addClass("was-validated");

此解决方案仅向无效输入添加红色边框。但是,一旦它们得到纠正,它们将显示为绿色边框,但就我个人而言,如果只有一个输入无效,我仍然更喜欢它而不是一片绿色的田野......