boostrap浮动标签与jquery验证标签冲突

问题描述 投票:0回答:2
html jquery jquery-validate bootstrap-5
2个回答
4
投票

用简单的脚本修复了这个问题。我在下面创建了一个片段:

$(document).ready(function() {
    $("#my_form").validate({
      rules: {
        name : {
          required: true
        }
      },
      messages : {
        name: "Please enter Name"
      },
      errorElement: "div",
        errorPlacement: function ( error, element ) {
            error.addClass( "invalid-feedback" );
            error.insertAfter( element );
        },
      highlight: function(element) {
        $(element).removeClass('is-valid').addClass('is-invalid');
      },
      unhighlight: function(element) {
        $(element).removeClass('is-invalid').addClass('is-valid');
      }
    });
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

<div class="container">
        <div class="row">
            <div class="col"></div>
            <div class="col-6">
                  <form action="" id="my_form" method="post">
                      <div class="form-floating mb-3">
                          <input type="text" class="form-control" placeholder="Name" name="name">
                          <label>Name</label>
                      </div>
                      <div class="col-12">
                          <button type="submit" class="btn btn-primary xp-submit-btn">Submit</button>
                      </div>
                  </form>
            </div>
            <div class="col"></div>
        </div>
    </div>


0
投票

您只需将

invalid-feedback
包含在
form-floating
元素内即可。就这样。它内置于引导程序中。

const $form = document.querySelector('#my-form');

$form.addEventListener('submit', (event) => {
    if (!$form.checkValidity()) {
      event.preventDefault();
      event.stopPropagation();
    }

    $form.classList.add('was-validated');
}, false);
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container mt-4">
  <form id="my-form" class="needs-validation" novalidate>
    <div class="form-floating mb-3">
      <input type="text" class="form-control" placeholder="Name" name="name" required>
      <label>Name</label>
      <div class="invalid-feedback">Please enter Name</div>
    </div>

    <button class="btn btn-primary" type="submit">Submit form</button>
  </form>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.