引导程序 - 验证


本章将讨论 Bootstrap 验证。Bootstrap 5 Validation 通过向用户提供有用的反馈、支持默认浏览器Behave、自定义样式和 JavaScript 来增强 HTML5 表单验证。

客户端自定义验证样式和工具提示无法访问,因为它们对辅助技术不可见。在我们研究解决方案时,建议使用服务器端选项或默认浏览器验证技术。

Bootstrap 中表单验证的工作原理

  • CSS 中的两个伪类:invalid:valid用于提供 HTML 表单验证。它适用于<textarea><select><input>元素。

  • Bootstrap 将:invalid:valid样式应用于父.was-validated类。页面加载时,没有值的字段显示为无效。您选择何时激活它们(通常在提交表单后)。

  • 要在使用 Ajax 动态提交后恢复表单的原始外观,应从<form>中删除.was-validated类以重置其外观。

  • 伪类可以替换为服务器端验证的.is-invalid.is-valid类作为后备,而不需要.was-validated父类。

  • 目前,CSS 限制阻止我们在没有自定义 JavaScript 帮助的情况下直接将样式应用于DOM 中表单控件之前的<label>元素。

  • 约束验证 API包含用于验证表单控件的各种 JavaScript 方法,所有现代 Web 浏览器都支持该约束验证 API。

  • 使用浏览器默认样式或使用 HTML/CSS 创建自定义反馈样式。

  • 在 JavaScript 中使用setCustomValidity方法来获取唯一的有效性消息。

让我们看一些自定义表单验证样式、可选服务器端类和浏览器默认值的示例。

定制款式

  • 将novalidate布尔属性添加到<form>以接收来自 Bootstrap 的自定义验证消息。

  • 使用上述布尔属性禁用浏览器默认反馈工具提示,但 JavaScript 验证 API 仍然有效。提交此表单将触发 JavaScript 提供反馈,在表单控件上显示:invalid:valid样式。

  • 自定义反馈样式通过添加颜色、边框、焦点样式和背景图标来改善反馈沟通。<select>的背景图标仅适用于.form-select,不适用于.form-control

此示例演示了具有验证功能的 Bootstrap 表单,以确保在提交表单之前正确填写必填字段。

例子

您可以使用编辑和运行选项编辑并尝试运行此代码。

  <!DOCTYPE html>
  <html lang="en">
  <head>
   <title>Bootstrap - Validation</title>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
   <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"></script>
  </head>
  <body>
   <form class="row g-3 needs-validation" novalidate>
     <div class="col-md-4">
       <label for="validationCustomName" class="form-label">Full Name</label>
       <input type="text" class="form-control" id="validationCustomName" value="Jhon Miller" required>
       <div class="invalid-feedback">
           Correct input!
       </div>
     </div>

     <div class="col-md-4">
       <label for="validationCustomEmail" class="form-label">Email Id</label>
       <div class="input-group has-validation">
         <input type="text" class="form-control" id="validationCustomEmail" aria-describedby="inputGroupPrepend" required>
         <span class="input-group-text" id="inputGroupPrepend">@tutorialspoint.com</span>
         <div class="invalid-feedback">
            Please enter correct mail id.
         </div>
       </div>
     </div>

     <div class="col-md-4">
       <label for="validationCustomPhone" class="form-label">Mobile no</label>
       <input type="text" class="form-control" id="validationCustomPhone" required>
       <div class="invalid-feedback">
          please enter correct mobile no.
       </div>
     </div>

     <div class="col-md-6">
       <label for="validationAddress" class="form-label">Address</label>
         <input type="text" class="form-control" id="validationAddress" value="XYZ - 123" required>
         <div class="valid-feedback">
          Correct input!
         </div>
       </div>
     </div>

     <div class="col-md-3">
       <label for="validationCustom" class="form-label">Gender</label>
       <select class="form-select" id="validationCustom" required>
         <option selected disabled value="">Choose...</option>
         <option>Male</option>
         <option>Female</option>
         <option>Others</option>
       </select>
       <div class="invalid-feedback">
          Please select gender.
       </div>
     </div>

     <div class="col-12">
       <div class="form-check">
         <input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
         <label class="form-check-label" for="invalidCheck">
            I have reviewed and agree to Terms of Services and Privacy Policy.
         </label>
         <div class="invalid-feedback">
            You must agree before submitting.
         </div>
       </div>
     </div>

     <div class="col-12">
       <button class="btn btn-primary" type="submit">Submit</button>
     </div>
   </form>
  <script>
    (() => {
    'use strict'

    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    const forms = document.querySelectorAll('.needs-validation')

    // Loop over them and prevent submission
    Array.from(forms).forEach(form => {
      form.addEventListener('submit', event => {
        if (!form.checkValidity()) {
          event.preventDefault()
          event.stopPropagation()
        }

        form.classList.add('was-validated')
      }, false)
    })
  })()
  </script>
  </body>
  </html>

如果存在无效字段,以下 JavaScript 代码片段将禁用表单提交。它通过向表单添加事件侦听器并在表单无效时阻止默认表单提交Behave来实现此目的。

    // Example JavaScript starter for disabling form submissions if there are invalid fields
    (() => {
      'use strict'

      // Fetch all the forms we want to apply custom Bootstrap validation styles to
      const forms = document.querySelectorAll('.needs-validation')

      // Loop over them and prevent submission
      Array.from(forms).forEach(form => {
        form.addEventListener('submit', event => {
          if (!form.checkValidity()) {
            event.preventDefault()
            event.stopPropagation()
          }

          form.classList.add('was-validated')
        }, false)
      })
    })()

浏览器默认设置

  • 我们还可以使用浏览器默认消息而不是自定义验证消息。根据您的浏览器和操作系统,反馈风格略有不同。

  • 尽管 CSS 不能用于设置这些反馈样式,但 JavaScript 仍可用于更改反馈文本。

尝试提交以下示例中的表单以了解默认浏览器验证消息的显示方式。

例子

您可以使用编辑和运行选项编辑并尝试运行此代码。

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <title>Bootstrap Form - Validation</title>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"></script>
    </head>
    <body>
      <form class="row g-3">
        <div class="col-md-4">
          <label for="validationDefaultName" class="form-label">Full Name</label>
          <input type="text" class="form-control" id="validationDefaultName" value="name" required>
        </div>
        <div class="col-md-4">
          <label for="validationDefaultEmail" class="form-label">Email Id</label>
          <div class="input-group">
            <input type="text" class="form-control" id="validationDefaultEmail" aria-describedby="inputGroupPrepend" required>
            <span class="input-group-text" id="inputGroupPrepend">@tutorialspoint.com</span>
          </div>
        </div>
        <div class="col-md-4">
          <label for="validationDefaultMob" class="form-label">Mobile No</label>
          <input type="text" class="form-control" id="validationDefaultMob" value="" required>
        </div>
        <div class="col-md-6">
          <label for="validationDefaultAddress" class="form-label">Address</label>
          <input type="text" class="form-control" id="validationDefaultAddress" required>
        </div>
        <div class="col-md-3">
          <label for="validationDefaultGender" class="form-label">Gender</label>
          <select class="form-select" id="validationDefaultGender" required>
            <option selected disabled value="">Choose...</option>
            <option>Male</option>
            <option>Female</option>
            <option>Others</option>
          </select>
        </div>
        <div class="form-check">
            <input class="form-check-input" type="checkbox" value="" id="invalidCheck2" required>
            <label class="form-check-label" for="invalidCheck2">
              I have reviewed and agree to Terms of Services and Privacy Policy.
            </label>
          </div>
        </div>
        <div class="col-12">
          <button class="btn btn-primary" type="submit">Submit</button>
        </div>
      </form>
    </body>
    </html>

服务器端

  • 建议使用客户端验证,但在服务器端验证的情况下,请使用.is-invalid.is-valid指令来指示表单字段状态。还可以考虑对这些类使用.invalid-feedback

  • 在无效字段的情况下,使用aria-scribedby属性将无效反馈/错误消息链接到表单字段。(如果字段连接到其他表单文本,则允许引用多个 id。)

  • 输入组需要额外的.has-validation类来处理边界半径问题

例子

您可以使用编辑和运行选项编辑并尝试运行此代码。

  <!DOCTYPE html>
  <html lang="en">
  <head>
    <title>Bootstrap - Validation</title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"></script>
  </head>
  <body>
    <form class="row g-3">
      <div class="col-md-4">
        <label for="validationServerName" class="form-label">Full name</label>
        <input type="text" class="form-control is-valid" id="validationServerName" value="Mark" required>
        <div class="valid-feedback">
          enter your name
        </div>
      </div>
      <div class="col-md-4">
        <label for="validationServerEmail" class="form-label">Email Id</label>
        <div class="input-group has-validation">
          <input type="text" class="form-control is-invalid" id="validationServerEmail"
            aria-describedby="inputGroupPrepend3 validationServerEmailFeedback" required>
          <span class="input-group-text" id="inputGroupPrepend3">@tutorialspoint.com</span>
          <div id="validationServerEmailFeedback" class="invalid-feedback">
            Please enter mail id.
          </div>
        </div>
      </div>
      <div class="col-md-4">
        <label for="validationServerMob" class="form-label">Mobile no</label>
        <input type="text" class="form-control is-valid" id="validationServerMob" value="" required>
        <div class="valid-feedback">
          Please enter mobile no
        </div>
      </div>
      <div class="col-md-6">
        <label for="validationServerAddress" class="form-label">Address</label>
        <input type="text" class="form-control is-invalid" id="validationServerAddress"
          aria-describedby="validationServerAddressFeedback" required>
        <div id="validationServerAddressFeedback" class="invalid-feedback">
          Please enter a valid Address.
        </div>
      </div>
      <div class="col-md-3">
        <label for="validationServer04" class="form-label">Gender</label>
        <select class="form-select is-invalid" id="validationServer04" aria-describedby="validationServer04Feedback"
          required>
          <option selected disabled value="">Choose...</option>
          <option>Male</option>
          <option>Female</option>
          <option>Others</option>
        </select>
        <div id="validationServer04Feedback" class="invalid-feedback">
          Please select a valid gender.
        </div>
      </div>
      <div class="col-12">
        <div class="form-check">
          <input class="form-check-input is-invalid" type="checkbox" value="" id="invalidCheckPolicy"
            aria-describedby="invalidCheckFeedback" required>
          <label class="form-check-label" for="invalidCheckPolicy">
            I have reviewed and agree to Terms of Services and Privacy Policy.
          </label>
          <div id="invalidCheckFeedback" class="invalid-feedback">
            You must agree before submitting.
          </div>
        </div>
      </div>
      <div class="col-12">
        <button class="btn btn-primary" type="submit">Submit</button>
      </div>
    </form>
  </body>
  </html>;

支持的元素

以下表单控件和组件支持验证样式:

  • <textarea><input> 使用.form-control(允许输入组最多包含一个.form-control)。

  • <select>使用.form-select

  • .表单检查

例子

您可以使用编辑和运行选项编辑并尝试运行此代码。

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <title>Bootstrap Form - Validation</title>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"></script>
    </head>
    <body>
      <form class="was-validated">
        <div class="mb-3">
          <label for="validationTextarea" class="form-label">Add comment</label>
          <textarea class="form-control" id="validationTextarea" placeholder="Comment Here" required></textarea>
          <div class="invalid-feedback">
            Add comment
          </div>
        </div>
        <div class="form-check mb-3">
          <input type="checkbox" class="form-check-input" id="validationFormCheck" required>
          <label class="form-check-label" for="validationFormCheck">Item One</label>
          <div class="invalid-feedback">Invalid Answer</div>
        </div>
        <div class="form-check">
          <input type="radio" class="form-check-input" id="validationFormRadio1" name="radio-stacked" required>
          <label class="form-check-label" for="validationFormRadio1">Item Two</label>
        </div>
        <div class="form-check mb-3">
          <input type="radio" class="form-check-input" id="validationFormRadio2" name="radio-stacked" required>
          <label class="form-check-label" for="validationFormRadio2">Item Three</label>
          <div class="invalid-feedback">Invalid Answer</div>
        </div>
        <div class="mb-3">
          <select class="form-select" required aria-label="select example">
            <option value="">Gender</option>
            <option value="1">Male</option>
            <option value="2">Female</option>
            <option value="3">Others</option>
          </select>
          <div class="invalid-feedback">Invalid selection</div>
        </div>
        <div class="mb-3">
          <input type="file" class="form-control" aria-label="file example" required>
          <div class="invalid-feedback">File size more than 256kb</div>
        </div>
        <div class="mb-3">
          <button class="btn btn-primary" type="submit" disabled>Submit</button>
        </div>
      </form>
    </body>
    </html>

工具提示

  • 要在样式化工具提示中显示验证反馈,请将.{valid|invalid}-feedback类交换为.{valid|invalid}-tooltip(如果布局允许)。

  • 要定位工具提示,请确保父级具有属性position:relative

例子

您可以使用编辑和运行选项编辑并尝试运行此代码。

  <!DOCTYPE html>
  <html lang="en">
  <head>
    <title>Bootstrap - Validation</title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"></script>
  </head>
  <body>
    <form class="row g-3 needs-validation" novalidate>
      <div class="col-md-4 position-relative">
        <label for="validationTooltipName" class="form-label">Full Name</label>
        <input type="text" class="form-control" id="validationTooltipName" value="Jhon Miller" required>
        <div class="valid-tooltip">
          Correct Input!
        </div>
      </div>
      <div class="col-md-4 position-relative">
        <label for="validationTooltipEmail" class="form-label">Email Id</label>
        <div class="input-group has-validation">
          <input type="text" class="form-control" id="validationTooltipEmail" aria-describedby="validationTooltipEmailPrepend" required>
          <span class="input-group-text" id="validationTooltipEmailPrepend">@tutorialspoint.com</span>
          <div class="invalid-tooltip">
           Please enter mail id.
          </div>
        </div>
      </div>
      <div class="col-md-4 position-relative">
        <label for="validationTooltipMob" class="form-label">Mobile no</label>
        <input type="text" class="form-control" id="validationTooltipMob" required>
        <div class="invalid-tooltip">
          Please enter mobile no.
        </div>
      </div>

      <div class="col-md-6 position-relative">
        <label for="validationTooltipAddress" class="form-label">Address</label>
        <input type="text" class="form-control" id="validationTooltipAddress" value="XYZ - 123" required>
        <div class="valid-tooltip">
         Correct Input!
        </div>
      </div>
      <div class="col-md-3 position-relative">
        <label for="validationTooltip04" class="form-label">Gender</label>
        <select class="form-select" id="validationTooltip04" required>
          <option selected disabled value="">Choose...</option>
          <option>Male</option>
          <option>Female</option>
          <option>Others</option>
        </select>
        <div class="invalid-tooltip">
          Please select a valid gender.
        </div>
      </div>

      </div>
      <div class="col-12">
        <button class="btn btn-primary" type="submit">Submit</button>
      </div>
    </form>
    <script>
      (() => {
    'use strict'

    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    const forms = document.querySelectorAll('.needs-validation')

    // Loop over them and prevent submission
    Array.from(forms).forEach(form => {
      form.addEventListener('submit', event => {
        if (!form.checkValidity()) {
          event.preventDefault()
          event.stopPropagation()
        }

        form.classList.add('was-validated')
      }, false)
    })
  })()
    </script>
  </body>
  </html>