以下是基于Bootstrap 5和jQuery的表单示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Bootstrap 5 Form Validation</title>
  <!-- Bootstrap 5 CSS -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css">
</head>
<body>
  <div class="container mt-5">
    <form id="my-form" class="needs-validation" novalidate>
      <div class="form-floating mb-3">
        <input type="password" class="form-control" id="password-input" name="password" placeholder="Password" minlength="6" required>
        <label for="password-input">Password</label>
        <div class="invalid-feedback">Password must be at least 6 characters.</div>
      </div>
      <button type="submit" class="btn btn-primary">Submit</button>
    </form>
  </div>
  <!-- Bootstrap 5 JS and jQuery -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    // Enable form validation with jQuery
    $('#my-form').on('submit', function(event) {
      if (this.checkValidity() === false) {
        event.preventDefault();
        event.stopPropagation();
      }
      this.classList.add('was-validated');
    });

    // Add custom validation for password
    $('#password-input').on('input', function() {
      var password = $(this).val();
      if (password.length < 6) {
        this.setCustomValidity('Password must be at least 6 characters.');
      } else {
        this.setCustomValidity('');
      }
    });
  </script>
</body>
</html>

在上面的代码中,我们使用了 Bootstrap 5 中的表单样式和验证方法,以及 jQuery 来实现自定义验证。具体来说,我们给表单添加了 needs-validation 类,以启用 Bootstrap 5 的内置表单验证。我们还添加了一个密码输入框,并设置了 minlength="6" 属性,以确保密码至少为 6 个字符。我们还添加了一个按钮,以提交表单。

在 JavaScript 部分,我们使用了 jQuery 的 on() 方法来监听表单的 submit 事件,并检查表单是否通过验证。如果表单未通过验证,则阻止默认提交行为,并显示验证错误信息。我们还添加了一个自定义验证函数,以检查密码是否至少为 6 个字符。这个函数使用了 setCustomValidity() 方法来设置自定义错误消息。

最后,我们需要注意在 HTML 中引入 Bootstrap 5 和 jQuery 的 CSS 和 JS 文件,以确保正确加载和使用相关库。

基于bootstrap5 生成一个form表单表单要求有一个按钮一个密码输入框并用js做验证密码不能为空密码必须为6个字符JS可以使用jquery

原文地址: https://www.cveoy.top/t/topic/b3de 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录