【问题标题】:Bootstrap 4 Form ValidationBootstrap 4 表单验证
【发布时间】:2017-04-18 20:04:49
【问题描述】:

我是 bootstrap 的初学者,我见过很多 bootstrap 3 表单验证插件等,但我没有找到任何适用于 bootstrap 4 的插件。

我正在尝试验证多个表单,这是我的代码:

<!-- Contact -->
<div class="container white">
  <div class="row">
    <div class="container white percent100">
      <div class="col-lg-12">
        <div class="padder-t2">
          <h1>Contact</h1>
          <div class="horiz-divider"></div>
        </div>
      </div>
    </div>
  </div>
  <div class="row padder-t padder-b">
    <div class="container white">
      <div class="col-lg-12">
        <!-- Form -->
        <form class="form-horizontal" action=" " method="post" id="contact_form">
          <fieldset>
            <!-- Text input-->
            <div class="form-group">
              <div class="row">
                <div class="col-md-4 col-lg-4">
                  <label class="control-label pull-right"><h4>First Name</h4></label>
                </div>
                <div class="col-md-4 col-lg-4 inputGroupContainer">
                  <div class="input-group">
                    <span class="input-group-addon"><i class="fa fa-user"></i></span>
                    <input id="firstname" name="firstname" placeholder="First Name" class="form-control" type="text">
                  </div>
                </div>
              </div>
            </div>
            <!-- Text input-->
            <div class="form-group">
              <div class="row">
                <div class="col-md-4 col-lg-4">
                  <label class="control-label pull-right"><h4>Last Name</h4></label>
                </div>
                <div class="col-md-4 col-lg-4 inputGroupContainer">
                  <div class="input-group">
                    <span class="input-group-addon"><i class="fa fa-user"></i></span>
                    <input id="lastname" name="lastname" placeholder="Last Name" class="form-control" type="text">
                  </div>
                </div>
              </div>
            </div>
            <!-- Text input-->
            <div class="form-group">
              <div class="row">
                <div class="col-md-4 col-lg-4">
                  <label class="control-label pull-right"><h4>E-Mail</h4></label>
                </div>
                <div class="col-md-4 col-lg-4 inputGroupContainer">
                  <div class="input-group">
                    <span class="input-group-addon"><i class="fa fa-envelope"></i></span>
                    <input id="email" name="email" placeholder="E-Mail Address" class="form-control" type="email">
                  </div>
                </div>
              </div>
            </div>
            <!-- Text input-->
            <div class="form-group">
              <div class="row">
                <div class="col-md-4 col-lg-4">
                  <label class="control-label pull-right"><h4>Phone #</h4></label>
                </div>
                <div class="col-md-4 col-lg-4 inputGroupContainer">
                  <div class="input-group">
                    <span class="input-group-addon"><i class="fa fa-phone"></i></span>
                    <input id="phone" name="phone" placeholder="Phone" class="form-control" type="text">
                  </div>
                </div>
              </div>
            </div>
            <!-- Text area -->
            <div class="form-group">
              <div class="row">
                <div class="col-md-4 col-lg-4">
                  <label class="control-label pull-right"><h4>Message</h4></label>
                </div>
                <div class="col-md-4 col-lg-5 inputGroupContainer">
                  <div class="input-group">
                    <span class="input-group-addon"><i class="fa fa-pencil"></i></span>
                    <textarea id="comment" class="form-control" name="comment" placeholder="Your Message"></textarea>
                  </div>
                </div>
              </div>
            </div>
            <!-- Success message -->
            <div class="alert alert-success" role="alert" id="success_message">Success <i class="fa fa-thumbs-up"></i> Thanks for contacting us, we will get back to you shortly.</div>
            <!-- Button -->
            <div class="form-group">
              <div class="row">
                <label class="col-md-4 col-lg-4 control-label"></label>
                <div class="col-md-4 col-lg-4">
                  <button type="submit" class="btn btn-danger raised">Send <i class="fa fa-paper-plane"></i></button>
                </div>
              </div>
            </div>
          </fieldset>
        </form>
      </div>
    </div>
  </div>
  <div class="row padder-b">
    <div class="row col-lg-12">
      <div class="col-md-3 col-lg-3"></div>
      <h4 class="col-md-9 col-lg-9">Contact us directly:</h4>
    </div>
    <div class="row col-lg-12">
      <div class="col-md-3 col-lg-3"></div>
      <h4 class="col-md-2 col-lg-2 padder-lr">Mail:</h4>
      <a class="col-md-6 col-lg-6 padder-lr" href="mailto:lorem@ipsum.com">
        <h4 id="mail">lorem@ipsum.com</h4>
      </a>
    </div>
    <div class="row col-lg-12">
      <div class="col-md-3 col-lg-3"></div>
      <h4 class="col-md-2 col-lg-2 padder-lr">Adress:</h4>
      <h4 class="col-md-6 col-lg-6 padder-lr" id="adress">2 LoremIpsum Road, 67000 City - Country</h4>
    </div>
  </div>
</div>

我曾尝试修改现有的 js,但我没有运气。

这是渲染的表格:

jsfiddle of the form

【问题讨论】:

标签: javascript jquery validation bootstrap-4 jquery-form-validator


【解决方案1】:

首先,我使用建议的Jonathan Dion 之类的外部库解决了我的问题。但最近我遇到了这个:

Bootstrap v4.0 引入了他们自己的表单验证,您仍然可以与后端 php 验证配对。来自Doc

<form class="needs-validation" novalidate>
  <div class="form-row">
    <div class="col-md-4 mb-3">
      <label for="validationCustom01">First name</label>
      <input type="text" class="form-control" id="validationCustom01" placeholder="First name" value="Mark" required>
      <div class="valid-feedback">
        Looks good!
      </div>
      <div class="invalid-feedback">
        Doesn't look good!
      </div>
    </div>
  </div>
</div>

然后使用JS:

<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(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>

这提供了输入边框着色并根据给定的模式或属性显示有效/无效的反馈块。它通过 CSS 的两个伪类:invalid:valid 应用。它适用于&lt;input&gt;&lt;select&gt;&lt;textarea&gt; 元素。

【讨论】:

  • 这对我有用,但我不得不更改我的表单标签。从
    实质上删除了控制器和操作属性。
【解决方案2】:

2020 年更新 - Bootstrap 4.4.x

如果您想一次验证每个输入(livereal-time)而不是等待整个表单提交...

(function() {
  'use strict';
  window.addEventListener('load', function() {
    // fetch all the forms we want to apply custom style
    var inputs = document.getElementsByClassName('form-control')

    // loop over each input and watch blur event
    var validation = Array.prototype.filter.call(inputs, function(input) {

      input.addEventListener('blur', function(event) {
        // reset
        input.classList.remove('is-invalid')
        input.classList.remove('is-valid')

        if (input.checkValidity() === false) {
            input.classList.add('is-invalid')
        }
        else {
            input.classList.add('is-valid')
        }
      }, false);
    });
  }, false);
})()

<form class="container" novalidate="" action="/echo" method="POST" id="myForm">
    <div class="form-group">
        <label class="form-control-label" for="input1">Enter some input</label>
        <input type="text" class="form-control" name="input1" id="input1" 
            autocomplete="no" required>
        <div class="valid-feedback">Success! You've done it.</div>
        <div class="invalid-feedback">No, you missed this one.</div>
    </div>
    <div class="form-group">
        <label class="form-control-label" for="input2">Enter password</label>
        <input type="text" class="form-control" 
            pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}$" 
            autocomplete="no" name="input2" id="input2">
        <div class="valid-feedback">Nice! You got this one!</div>
        <div class="invalid-feedback">At least 6 chars: 1 uppercase, 1 lowercase and numeric</div>
    </div>
    <div>
        <button type="submit" class="btn btn-secondary" id="btnSubmit">Submit</button>
    </div>
</form>

https://codeply.com/p/mzBNbAlOvQ

【讨论】:

  • 此方法忽略 minlength 和 maxlength
  • 问题是否提到了最小值和最大值?
  • 也不会在提交时替换完整的表单验证。使用 novalidate 禁用所有 html5 输入验证(必需、模式、最小/最大),它基本上不会阻止提交空表单,甚至没有禁用按钮,必须与下面的答案一起使用/配对才能体面(在表单上提交)
【解决方案3】:

您可以使用网络上的任何库。您可以尝试jqueryvalidation。它非常易于使用,只需阅读文档即可。

input 上添加required 属性,jqueryvalidation 将完成这项工作。对于样式,您可以添加自己的 CSS 并使其看起来像引导程序。

希望对你有帮助

$(document).ready(function(){
 $('#contact_form').validate()
})

Demo

【讨论】:

  • 这就是我尝试过的,但它不适用于我的布局,它会在我输入后立即添加消息,我现在不知道如何在表单组下强制添加...
  • 如果您仅将名称放入,则您的示例在提交时不起作用。
  • 您只需要在输入中添加required
【解决方案4】:

我刚刚弄清楚我的代码没有验证的原因:我没有提交按钮来触发验证。确保拥有它。

<button type="submit" class="btn btn-primary">Save</button>

【讨论】:

  • 请注意,提交按钮不是“必需”来验证表单字段。
【解决方案5】:

我找到了一种更简单、更现代的方式来实现Bootstrap 4 JS Form validation

注意:请记住,每个&lt;form&gt; 元素必须具有novalidate 属性,同时其中的每个&lt;input&gt; 元素必须具有required 属性。

// Upon load..
window.addEventListener('load', () => {

  // Grab all the forms
  var forms = document.getElementsByClassName('needs-validation');
  
  // Iterate over each one
  for (let form of forms) {
  
    // Add a 'submit' event listener on each one
    form.addEventListener('submit', (evt) => {
    
      // check if the form input elements have the 'required' attribute  
      if (!form.checkValidity()) {
        evt.preventDefault();
        evt.stopPropagation();
        console.log('Bootstrap will handle incomplete form fields');
      } else {
        // Since form is now valid, prevent default behavior..
        evt.preventDefault();
        console.info('All form fields are now valid...');
      }
      
      form.classList.add('was-validated');
      
    });
    
  }
  
});
<!-- Load necessary libraries -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<!-- Add form -->
<div class="container" style="padding-top: 40px;">
  <form class="student-search needs-validation" novalidate>
    <div class="form-row">
      <div class="form-group col-6">
        <label for="input-name-search" class="sr-only">Name</label>
        <input type="text" class="form-control" id="input-name-search" placeholder="Name" required>
        <div class="valid-feedback">Looks good!</div>
        <div class="invalid-feedback">Enter a name please.</div>
      </div>
      <div class="col-6">
        <button id="btn-search" type="submit" class="btn btn-success btn-block">Search student</button>
      </div>
    </div>
  </form>
</div>

【讨论】:

    【解决方案6】:

    这里不需要库,你可以使用原生的reportValidation() 方法:MDN。您可以在单个输入或整个表单本身上调用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      • 2019-11-17
      • 2018-07-25
      • 2018-05-15
      • 2020-06-12
      • 1970-01-01
      • 2018-09-13
      相关资源
      最近更新 更多