Has error bootstrap

На этом уроке мы рассмотрим, как можно с помощью классов Twitter Bootstrap 3 изменять состояние элементов управления формы при её проверке с помощью встроенных средств HT

На этом уроке мы рассмотрим, как можно с помощью классов Twitter Bootstrap 3 изменять состояние элементов управления формы при её проверке с помощью встроенных средств HTML5.

Использование классов Twitter Bootstrap 3 для отображения результатов проверки формы

Перед отправкой формы на сервер, её заполнение обычно проверяют с помощью скриптов JavaScript или встроенного в HTML 5 метода checkValidity(). Эта процедура исключает обработку сервером неверно заполненных данных пользователем, а также разгружает сервер посредством уменьшения количества запросов к нему.

На этом уроке, для проверки правильности заполнения полей формы, мы будем использовать встроенный в HTML 5 метод checkValidity(). А подсказывать пользователю, правильно ли он заполнил поле или нет в форме, будем с помощью классов Twitter Bootstrap 3 .has-warning, .has-error и has.success.

В качестве примера рассмотрим форму для регистрации, которую будем открывать в модальном окне с помощью соответствующей кнопки на веб-странице.

Процесс создания формы и её валидации представим в виде следующих шагов:

  1. Создадим форму для регистрации пользователя.

    Для отображения иконки (в области c), показывающей результат валидации данных, необходимо добавить класс .has-feedback к контейнеру <div class="form-group"></div> и элемент <span class="glyphicon form-control-feedback"></span> для каждого блока формы.

    Bootstrap - создание форму для регистрации пользователя

    <!-- Форма для регистрации -->
    <form role="form" class="form-horizontal">
      <!-- Блок для ввода логина -->
      <div class="form-group has-feedback">
        <label for="login" class="control-label col-xs-3">Логин:</label>
        <div class="col-xs-6">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
    	<input type="text" class="form-control" required="required" name="login" pattern="[A-Za-z]{6,}">
          </div>
          <span class="glyphicon form-control-feedback"></span>
        </div>
      </div>
      <!-- Блок для ввода email -->
      <div class="form-group has-feedback">
        <label for="email" class="control-label col-xs-3">Email:</label>
        <div class="col-xs-6">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
    	<input type="email" class="form-control" required="required" name="email">
          </div>
          <span class="glyphicon form-control-feedback"></span>
        </div>
      </div>
      <!-- Конец блока для ввода email-->
    </form>
  2. Создадим модальное окно, содержащее форму для регистрации

    Bootstrap - создание модального окна, содержащее форму для регистрации

    <!-- Модальное окно -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <!-- Заголовок модального окна -->
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">×</button>
            <h4 class="modal-title" id="myModalLabel">Регистрация</h4>
          </div>
          <!-- Основная часть модального окна, содержащая форму для регистрации -->
          <div class="modal-body">
            <!-- Форма для регистрации -->
      	<form role="form" class="form-horizontal">
    	  <!-- Блок для ввода логина -->
    	  <div class="form-group has-feedback">
    	    <label for="login" class="control-label col-xs-3">Логин:</label>
    	    <div class="col-xs-6">
    	      <div class="input-group">
    	        <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
    	        <input type="text" class="form-control" required="required" name="login" pattern="[A-Za-z]{6,}">
    	      </div>
    	      <span class="glyphicon form-control-feedback"></span>
    	    </div>
    	  </div>
    	  <!-- Блок для ввода email -->
    	  <div class="form-group has-feedback">
    	    <label for="email" class="control-label col-xs-3">Email:</label>
    	    <div class="col-xs-6">
    	      <div class="input-group">
    	        <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
    	        <input type="email" class="form-control" required="required" name="email">
    	      </div>
    	      <span class="glyphicon form-control-feedback"></span>
    	    </div>
    	  </div>
              <!-- Конец блока для ввода email-->
            </form>
          </div>
          <!-- Нижняя часть модального окна -->
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
            <button id="save" type="button" class="btn btn-primary">Регистрация</button>
          </div>
        </div>
      </div>
    </div>
  3. Создадим кнопку для вызова модального окна.

    Bootstrap - кнопка для открытия модального окна

    <!-- Кнопка для открытия модального окна -->
    <button type="button" class="btn btn-lg btn-success" data-toggle="modal" data-target="#myModal">
      Регистрация
    </button>
  4. Создадим сообщение, которое будет отображаться при закрытии модального окна. Сообщение будет отображаться только в том случае, если пользователь нажал на кнопку «Регистрация» и форма в этот момент валидна.

    Bootstrap - сообщение в случае успешной регистрации пользователя

    <div class="alert alert-success hidden" id="success-alert">
      <h2>Успех</h2>
      <div>Ваши данные были успешно отправлены.</div>
    </div>
  5. Напишем скрипт, который будет проверять данные в элементах управления формы на правильность заполнения с помощью метода HTML5 checkValidity().

    В зависимости от результата проверки данных в элементах управления формы, мы будем добавлять к ним одни классы, и удалять другие.

    Т.е. если данные в элементе управления не валидны, то мы выполняем следующее:

    • добавляем класс .has-error к элементу div (контейнеру с классом .form-group, в котором расположен данный элемент управления) и удаляем у него класс .has-success.
    • добавляем класс .glyphicon-remove к элементу span (элементу с классом .form-control-feedback, который предназначенный для отображения дополнительного значка) и удаляем у него класс .glyphicon-ok.

    Bootstrap - форма не прошла валидацию

    А если данные в элементе управления валидны, то мы выполняем всё наоборот, т.е.:

    • добавляем класс .has-success к элементу div (контейнеру с классом .form-group, в котором расположен данный элемент управления) и удаляем у него класс .has-error.
    • добавляем класс .glyphicon-ok к элементу span (элементу с классом .form-control-feedback, который предназначенный для отображения дополнительного значка) и удаляем у него класс .glyphicon-remove.

    Bootstrap - форма прошла валидацию

    <script>
      $(function() {
        //при нажатии на кнопку с id="save"
        $('#save').click(function() {
          //переменная formValid
          var formValid = true;
          //перебрать все элементы управления input
          $('input').each(function() {
          //найти предков, которые имеют класс .form-group, для установления success/error
          var formGroup = $(this).parents('.form-group');
          //найти glyphicon, который предназначен для показа иконки успеха или ошибки
          var glyphicon = formGroup.find('.form-control-feedback');
          //для валидации данных используем HTML5 функцию checkValidity
          if (this.checkValidity()) {
            //добавить к formGroup класс .has-success, удалить has-error
            formGroup.addClass('has-success').removeClass('has-error');
            //добавить к glyphicon класс glyphicon-ok, удалить glyphicon-remove
            glyphicon.addClass('glyphicon-ok').removeClass('glyphicon-remove');
          } else {
            //добавить к formGroup класс .has-error, удалить .has-success
            formGroup.addClass('has-error').removeClass('has-success');
            //добавить к glyphicon класс glyphicon-remove, удалить glyphicon-ok
            glyphicon.addClass('glyphicon-remove').removeClass('glyphicon-ok');
            //отметить форму как невалидную
            formValid = false;
          }
        });
        //если форма валидна, то
        if (formValid) {
          //сркыть модальное окно
          $('#myModal').modal('hide');
          //отобразить сообщение об успехе
          $('#success-alert').removeClass('hidden');
        }
      });
    });
    </script>

    Bootstrap - валидация данных формы

  6. В итоге у нас получился следующий код:

    <!--...-->
    <!-- Подлючаем CSS файл Bootstrap -->
    <link href="bootstrap.min.css" rel="stylesheet">
    <!--...-->
    
    <!-- Модальное окно -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <!-- Заголовок модального окна -->
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">×</button>
            <h4 class="modal-title" id="myModalLabel">Регистрация</h4>
          </div>
          <!-- Основная часть модального окна, содержащая форму для регистрации -->
          <div class="modal-body">
            <!-- Форма для регистрации -->
      	<form role="form" class="form-horizontal">
    	  <!-- Блок для ввода логина -->
    	  <div class="form-group has-feedback">
    	    <label for="login" class="control-label col-xs-3">Логин:</label>
    	    <div class="col-xs-6">
    	      <div class="input-group">
    	        <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
    	        <input type="text" class="form-control" required="required" name="login" pattern="[A-Za-z]{6,}">
    	      </div>
    	      <span class="glyphicon form-control-feedback"></span>
    	    </div>
    	  </div>
    	  <!-- Блок для ввода email -->
    	  <div class="form-group has-feedback">
    	    <label for="email" class="control-label col-xs-3">Email:</label>
    	    <div class="col-xs-6">
    	      <div class="input-group">
    	        <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
    	        <input type="email" class="form-control" required="required" name="email">
    	      </div>
    	      <span class="glyphicon form-control-feedback"></span>
    	    </div>
    	  </div>
              <!-- Конец блока для ввода email-->
            </form>
          </div>
          <!-- Нижняя часть модального окна -->
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
            <button id="save" type="button" class="btn btn-primary">Регистрация</button>
          </div>
        </div>
      </div>
    </div>
    
    <div class="container">
      <div class="alert alert-success hidden" id="success-alert">
        <h2>Успех</h2>
        <div>Ваши данные были успешно отправлены.</div>
      </div>
      <!-- Кнопка для открытия модального окна -->
      <button type="button" class="btn btn-lg btn-success" data-toggle="modal" data-target="#myModal">
        Регистрация
      </button>
    </div>
    
    <!-- Подлючаем библиотеку jQuery -->
    <script src="/assets/demo/jquery/jquery-1.11.2.min.js"></script>
    <!-- Подлючаем js файл Bootstrap -->
    <script src="/assets/demo/bootstrap-3/js/bootstrap.min.js"></script>
    
    <script>
      $(function() {
        //при нажатии на кнопку с id="save"
        $('#save').click(function() {
          //переменная formValid
          var formValid = true;
          //перебрать все элементы управления input
          $('input').each(function() {
          //найти предков, которые имеют класс .form-group, для установления success/error
          var formGroup = $(this).parents('.form-group');
          //найти glyphicon, который предназначен для показа иконки успеха или ошибки
          var glyphicon = formGroup.find('.form-control-feedback');
          //для валидации данных используем HTML5 функцию checkValidity
          if (this.checkValidity()) {
            //добавить к formGroup класс .has-success, удалить has-error
            formGroup.addClass('has-success').removeClass('has-error');
            //добавить к glyphicon класс glyphicon-ok, удалить glyphicon-remove
            glyphicon.addClass('glyphicon-ok').removeClass('glyphicon-remove');
          } else {
            //добавить к formGroup класс .has-error, удалить .has-success
            formGroup.addClass('has-error').removeClass('has-success');
            //добавить к glyphicon класс glyphicon-remove, удалить glyphicon-ok
            glyphicon.addClass('glyphicon-remove').removeClass('glyphicon-ok');
            //отметить форму как невалидную
            formValid = false;
          }
        });
        //если форма валидна, то
        if (formValid) {
          //сркыть модальное окно
          $('#myModal').modal('hide');
          //отобразить сообщение об успехе
          $('#success-alert').removeClass('hidden');
        }
      });
    });
    </script>
    <!--...-->

    Демо

Содержание

  1. Bootstrap 3 — Валидация формы
  2. Использование классов Twitter Bootstrap 3 для отображения результатов проверки формы
  3. Validation
  4. How it works
  5. Browser defaults
  6. Server side
  7. Supported elements
  8. Tooltips
  9. Variables
  10. Mixins
  11. Customizing
  12. Bootstrap Form Inputs (more)
  13. Static Control
  14. Example
  15. Bootstrap Input Groups
  16. Example
  17. Example
  18. Bootstrap Form Control States
  19. Example
  20. Обзор
  21. HTML5 doctype
  22. В первую очередь — мобильные
  23. Типография и ссылки
  24. Normalize.css
  25. Контейнеры
  26. Разметка. Система сетки.
  27. Введение
  28. Медиа запросы
  29. Функционал разметки
  30. Пример: Сложенные по горизонтали
  31. Обзор
  32. HTML5 doctype
  33. Сначала мобильные
  34. Типография и ссылки
  35. Normalize.css
  36. Контейнеры
  37. Система сеток
  38. Вступление
  39. Медиа-запросы
  40. Параметры сетки
  41. Пример: с накоплением по горизонтали

Bootstrap 3 — Валидация формы

На этом уроке мы рассмотрим, как можно с помощью классов Twitter Bootstrap 3 изменять состояние элементов управления формы при её проверке с помощью встроенных средств HTML5.

Использование классов Twitter Bootstrap 3 для отображения результатов проверки формы

Перед отправкой формы на сервер, её заполнение обычно проверяют с помощью скриптов JavaScript или встроенного в HTML 5 метода checkValidity() . Эта процедура исключает обработку сервером неверно заполненных данных пользователем, а также разгружает сервер посредством уменьшения количества запросов к нему.

На этом уроке, для проверки правильности заполнения полей формы, мы будем использовать встроенный в HTML 5 метод checkValidity() . А подсказывать пользователю, правильно ли он заполнил поле или нет в форме, будем с помощью классов Twitter Bootstrap 3 .has-warning , .has-error и has.success .

Процесс создания формы и её валидации представим в виде следующих шагов:

Создадим форму для регистрации пользователя.

Создадим модальное окно, содержащее форму для регистрации

Создадим кнопку для вызова модального окна.

Создадим сообщение, которое будет отображаться при закрытии модального окна. Сообщение будет отображаться только в том случае, если пользователь нажал на кнопку «Регистрация» и форма в этот момент валидна.

Напишем скрипт, который будет проверять данные в элементах управления формы на правильность заполнения с помощью метода HTML5 checkValidity() .

В зависимости от результата проверки данных в элементах управления формы, мы будем добавлять к ним одни классы, и удалять другие.

Т.е. если данные в элементе управления не валидны, то мы выполняем следующее:

  • добавляем класс .has-error к элементу div (контейнеру с классом .form-group , в котором расположен данный элемент управления) и удаляем у него класс .has-success .
  • добавляем класс .glyphicon-remove к элементу span (элементу с классом .form-control-feedback , который предназначенный для отображения дополнительного значка) и удаляем у него класс .glyphicon-ok .

А если данные в элементе управления валидны, то мы выполняем всё наоборот, т.е.:

  • добавляем класс .has-success к элементу div (контейнеру с классом .form-group , в котором расположен данный элемент управления) и удаляем у него класс .has-error .
  • добавляем класс .glyphicon-ok к элементу span (элементу с классом .form-control-feedback , который предназначенный для отображения дополнительного значка) и удаляем у него класс .glyphicon-remove .

Источник

Validation

Provide valuable, actionable feedback to your users with HTML5 form validation, via browser default behaviors or custom styles and JavaScript.

How it works

Here’s how form validation works with Bootstrap:

    HTML form validation is applied via CSS’s two pseudo-classes, :invalid and :valid . It applies to , , and

elements.
Bootstrap scopes the :invalid and :valid styles to parent .was-validated class, usually applied to the

Browser defaults

Not interested in custom validation feedback messages or writing JavaScript to change form behaviors? All good, you can use the browser defaults. Try submitting the form below. Depending on your browser and OS, you’ll see a slightly different style of feedback.

While these feedback styles cannot be styled with CSS, you can still customize the feedback text through JavaScript.

Server side

We recommend using client-side validation, but in case you require server-side validation, you can indicate invalid and valid form fields with .is-invalid and .is-valid . Note that .invalid-feedback is also supported with these classes.

For invalid fields, ensure that the invalid feedback/error message is associated with the relevant form field using aria-describedby (noting that this attribute allows more than one id to be referenced, in case the field already points to additional form text).

To fix issues with border radii, input groups require an additional .has-validation class.

Supported elements

Validation styles are available for the following form controls and components:

s with .form-control (including up to one .form-control in input groups)

  • s with .form-select
  • .form-check s
  • If your form layout allows it, you can swap the .-feedback classes for .-tooltip classes to display validation feedback in a styled tooltip. Be sure to have a parent with position: relative on it for tooltip positioning. In the example below, our column classes have this already, but your project may require an alternative setup.

    Variables

    Mixins

    Two mixins are combined together, through our loop, to generate our form validation feedback styles.

    This is the validation Sass map from _variables.scss . Override or extend this to generate different or additional states.

    Maps of $form-validation-states can contain three optional parameters to override tooltips and focus styles.

    Used to iterate over $form-validation-states map values to generate our validation styles. Any modifications to the above Sass map will be reflected in your compiled CSS via this loop.

    Customizing

    Validation states can be customized via Sass with the $form-validation-states map. Located in our _variables.scss file, this Sass map is how we generate the default valid / invalid validation states. Included is a nested map for customizing each state’s color, icon, tooltip color, and focus shadow. While no other states are supported by browsers, those using custom styles can easily add more complex form feedback.

    Please note that we do not recommend customizing $form-validation-states values without also modifying the form-validation-state mixin.

    Bootstrap

    • Designed and built with all the love in the world by the Bootstrap team with the help of our contributors.
    • Code licensed MIT, docs CC BY 3.0.
    • Currently v5.0.2.
    • Analytics by Fathom.

    Источник

    Bootstrap Form Inputs (more)

    Static Control

    If you need to insert plain text next to a form label within a horizontal form, use the .form-control-static class on a

    Example

    Bootstrap Input Groups

    The .input-group class is a container to enhance an input by adding an icon, text or a button in front or behind it as a «help text».

    The .input-group-addon class attaches an icon or help text next to the input field.

    Example

    The .input-group-btn attaches a button next to an input. This is often used together with a search bar:

    Example

    Bootstrap Form Control States

    • INPUT FOCUS — The outline of the input is removed and a box-shadow is applied on focus
    • DISABLED INPUTS — Add a disabled attribute to disable an input field
    • DISABLED FIELDSETS — Add a disabled attribute to a fieldset to disable all controls within
    • READONLY INPUTS — Add a readonly attribute to an input to prevent user input
    • VALIDATION STATES — Bootstrap includes validation styles for error, warning, and success messages. To use, add .has-warning , .has-error , or .has-success to the parent element
    • ICONS — You can add feedback icons with the .has-feedback class and an icon
    • HIDDEN LABELS — Add a .sr-only class on non-visible labels

    The following example demonstrates some of the form control states above in a Horizontal form:

    Example

    And here is an example of some of the form control states in an Inline form:

    Источник

    Обзор

    Получите подробную информацию о ключевых элементах инфраструктуры Bootstrap, в том числе о нашем подходе к созданию более качественных, быстрых и мощных веб-приложений.

    HTML5 doctype

    В Bootstrap используются некоторые элементы HTML и свойства CSS, которые требуют использования HTML5 doctype. Включайте его в начале всех проектов.

    В первую очередь — мобильные

    В Bootstrap 2 мы внедряли возможности адаптирования сайтов для мобильных устройств. Приложение Bootstrap 3 изначально рассчитано на работу с мобильными устройствами. Вместо того чтобы добавлять дополнительные шаблоны для мобильных устройств, мы встроили их в ядро программы. Bootstrap в первую очередь рассчитан на мобильные устройства. Макеты для мобильных устройств хранятся в библиотеке, а не отдельными файлами.

    Чтобы обеспечить надлежащий рендеринг и изменение размера касанием, добавьте метатег viewport в ваш .

    Вы можете ограничить возможности приближения на мобильных устройствах добавляя user-scalable=no в мета тег видимого экрана. Это ограничит приближение, означающее что пользователи могут только скроллить, и результат на вашем сайте будет чувствоваться как нативное приложение. В любом случае, мы не рекомендуем это на каждом сайте, используйте с осторожностью.

    Типография и ссылки

    Bootstrap устанавливает основное глобальное отображение, типографику и стили ссылок:

    • Устанавливает background-color: #fff; на body
    • Использует @font-family-base , @font-size-base и @line-height-base атрибуты как нашу типографическую базу
    • Устанавливает цвет глобальных ссылок через @link-color и применяет подчеркивание ссылок только на :hover

    Эти стили можно найти в scaffolding.less .

    Normalize.css

    Для улучшения кросс-браузерного рендеринга, мы используем Normalize.css, проект от Nicolas Gallagher и Jonathan Neal.

    Контейнеры

    Простое центрирование контента страницы включая это содержимое в .container . Контейнер установлен в width на различных контрольных точках медиа запросов для соответствия с нашей системой разметки.

    Следует отметить, что, благодаря padding и фиксированной ширины, контейнеры не вложены по умолчанию.

    Разметка. Система сетки.

    Bootstrap включает в себя адаптивную, первую мобильную резиновую систему разметки, которая масштабируется до 12 столбцов как на устройствах или при изменении окна просмотра. Она включает в себя как для простых вариантов планировки, так и мощных для создания более смысловых макетов.

    Введение

    Система разметки используются для создания макетов страниц с помощью ряда строк и столбцов, в которых размещается ваш контент. Вот так работает система разметки Bootstrap:

    • .row должны быть помещены в .container (fixed-width) или .container-fluid (full-width) для правильного выравнивания и заполнения.
    • Использовать строки для создания горизонтальных группы столбцов.
    • Контент должен быть помещен в столбцах, и только колонки могут быть непосредственными потомками строк.
    • Стандартные классы разметки как .row и .col-xs-4 доступны для быстрого принятия разметки макетов. Less Mixins также может быть использован для более семантических схем.
    • Столбцы создают желоба (промежутки между содержанием столбцов) с помощью padding . Тогда padding компенсируется в строках для первого и последнего столбца с помощью отрицательного margin на .row .
    • Столбцы разметки создаются с указанием количества двенадцати доступных столбцов, которые вы хотите охватить. Например, три равные колонки использовали бы три .col-xs-4 .

    Посмотрите на примеры применения этих принципов в код.

    Медиа запросы

    Мы используем следующие медиа запросы в наших Less файлах, чтобы создать определяющую контрольную точку в нашей системе разметки.

    Мы иногда расширяем медиа запросы для включения max-width , чтобы ограничить CSS до более узкого набора устройств.

    Функционал разметки

    Посмотрите, как аспекты системы рзметки Bootstrap работают между несколькими устройствами с управляемой таблицей.

    Очень маленькие устройство Телефоны ( .col-xs- .col-sm- .col-md- .col-lg-
    # колонок 12
    Ширина колонки Авто 60px 78px 95px
    Промежуточная ширина 30px(15px) на каждой стороне колонки
    Вкладка Да
    Отступ Да
    Выравнивание колонки Да

    Классы разметки относятся к устройствам с экраном шириной, превышающим или равным крайним точкам размеров, и переопределяемые классы разметки ориентированых на небольшие устройства. Поэтому, применяя любой .col-md- класс к элементу не только влияет на его стиль на средних устройств, но и на больших устройств, если класс .col-lg- упущен.

    Пример: Сложенные по горизонтали

    Используя единичный набор .col-md-* классовой разметки, вы можете создать базовую систему разметки, которая запускается одновременно на мобильные устройства и планшетные устройства (от экстра маленьких до малых диапазонов) до того как выстроится горизонталь на рабочем столе (средних) устройств. Разместите столбцы разметки в любом .row .

    Источник

    Обзор

    Узнайте о ключевых элементах инфраструктуры Bootstrap, в том числе о нашем подходе к лучшей, быстрой и надежной веб-разработке.

    HTML5 doctype

    Bootstrap использует определенные элементы HTML и свойства CSS, которые требуют использования типа документа HTML5. Включите его в начало всех ваших проектов.

    Сначала мобильные

    В Bootstrap 2 мы добавили дополнительные удобные для мобильных устройств стили для ключевых аспектов фреймворка. В Bootstrap 3 мы с самого начала переписали проект, чтобы он был удобен для мобильных устройств. Вместо добавления дополнительных мобильных стилей они встроены прямо в ядро. Фактически, Bootstrap в первую очередь является мобильным. Стили Mobile first можно найти во всей библиотеке, а не в отдельных файлах.

    Чтобы обеспечить правильный рендеринг и масштабирование при касании, добавьте метатег области просмотра в свой .

    Вы можете отключить возможности масштабирования на мобильных устройствах, добавив user-scalable=no в метатег области просмотра. Это отключает масштабирование, то есть пользователи могут только прокручивать, и в результате ваш сайт будет больше похож на собственное приложение. В целом мы не рекомендуем это делать на всех сайтах, поэтому будьте осторожны!!

    Типография и ссылки

    Bootstrap устанавливает основные глобальные стили отображения, типографики и ссылок. В частности, мы:

    • Установите background-color: #fff; в body
    • Используйте атрибуты @font-family-base , @font-size-base и @line-height-base в качестве нашей типографской основы
    • Установите глобальный цвет ссылки через @link-color и примените подчеркивание ссылок только на :hover

    Эти стили можно найти в scaffolding.less .

    Normalize.css

    Для улучшения кроссбраузерности рендеринга мы используем Normalize.css, проект Николас Галлахер и Джонатан Нил.

    Контейнеры

    Bootstrap требует, чтобы вмещающий элемент обернул содержимое сайта и разместил нашу сетку. Вы можете выбрать один из двух контейнеров для использования в своих проектах. Обратите внимание, что из-за padding и т. д. ни один из контейнеров не может быть вложенным.

    Используйте .container для адаптивного контейнера фиксированной ширины.

    Используйте .container-fluid для контейнера полной ширины, охватывающего всю ширину области просмотра.

    Система сеток

    Bootstrap включает в себя адаптивную мобильную первую систему гибкой сетки, которая соответствующим образом масштабирует до 12 столбцов по мере увеличения размера устройства или области просмотра. Он включает предопределенные классы для простых вариантов макета, а также мощные миксины для создания более семантических макетов.

    Вступление

    Системы сетки используются для создания макетов страниц с помощью ряда строк и столбцов, в которых размещается ваш контент. Вот как работает сетка Bootstrap:

    • Строки должны быть помещены в .container (фиксированная ширина) или .container-fluid (во всю ширину) для правильного выравнивания и заполнения.
    • Используйте строки для создания горизонтальных групп столбцов.
    • Содержимое следует размещать внутри столбцов, и только столбцы могут быть непосредственными дочерними элементами строк.
    • Предопределенные классы сетки, такие как .row и .col-xs-4 , доступны для быстрого создания макетов сетки. Меньшее количество миксинов также можно использовать для более семантических макетов
    • Столбцы создают промежутки (промежутки между содержимым столбца) с помощью padding . Это заполнение смещено в строках для первого и последнего столбца посредством отрицательного поля на .row .
    • Из-за отрицательного поля приведенные ниже примеры неактуальны. Это значит, что содержимое столбцов сетки совмещается с содержимым, не относящимся к сетке.
    • Столбцы сетки создаются путем указания числа из двенадцати доступных столбцов, которые вы хотите охватить. Например, для трех равных столбцов будет использоваться три .col-xs-4 .
    • Если в одной строке помещается более 12 столбцов, каждая группа дополнительных столбцов как одно целое переносится на новую строку.
    • Классы сетки применяются к устройствам с шириной экрана больше или равной размеру точки останова и переопределяют классы сетки, нацеленные на устройства меньшего размера. Поэтому, например, применение любого класса .col-md-* к элементу повлияет не только на его стиль на средних устройствах, но и на больших устройствах, если класс .col-lg-* не предоставлен.

    Посмотрите примеры применения этих принципов к вашему коду.

    Мы используем следующие медиа-запросы в наших файлах Less для создания ключевых точек останова в нашей сеточной системе.

    Иногда мы расширяем эти медиа-запросы, чтобы включить max-width , чтобы ограничить CSS более узким набором устройств.

    Параметры сетки

    Посмотрите, как аспекты сеточной системы Bootstrap работают на нескольких устройствах с помощью удобной таблицы.

    97px

    Очень маленькие устройства Телефоны ( .col-xs- .col-sm- .col-md- .col-lg-
    # столбцов 12
    Ширина колонки Авто
    Ширина промежутка 30px (15px с каждой стороны столбца)
    Вложенный Да
    Смещения Да
    Порядок столбцов Да

    Пример: с накоплением по горизонтали

    Используя один набор классов сетки .col-md-* , вы можете создать базовую систему сетки, которая начинается на мобильных устройствах и планшетах (от очень малого до небольшого диапазона), а затем становится горизонтальной на настольные (средние) устройства. Поместите столбцы сетки в любой .row .

    Источник

    We are aware that currently the client-side custom validation styles and tooltips are not accessible, since they are not exposed to assistive technologies. While we work on a solution, we’d recommend either using the server-side option or the default browser validation method.

    How it works

    Here’s how form validation works with Bootstrap:

    • HTML form validation is applied via CSS’s two pseudo-classes, :invalid and :valid. It applies to <input>, <select>, and <textarea> elements.
    • Bootstrap scopes the :invalid and :valid styles to parent .was-validated class, usually applied to the <form>. Otherwise, any required field without a value shows up as invalid on page load. This way, you may choose when to activate them (typically after form submission is attempted).
    • To reset the appearance of the form (for instance, in the case of dynamic form submissions using AJAX), remove the .was-validated class from the <form> again after submission.
    • As a fallback, .is-invalid and .is-valid classes may be used instead of the pseudo-classes for server-side validation. They do not require a .was-validated parent class.
    • Due to constraints in how CSS works, we cannot (at present) apply styles to a <label> that comes before a form control in the DOM without the help of custom JavaScript.
    • All modern browsers support the constraint validation API, a series of JavaScript methods for validating form controls.
    • Feedback messages may utilize the browser defaults (different for each browser, and unstylable via CSS) or our custom feedback styles with additional HTML and CSS.
    • You may provide custom validity messages with setCustomValidity in JavaScript.

    With that in mind, consider the following demos for our custom form validation styles, optional server-side classes, and browser defaults.

    Custom styles

    For custom Bootstrap form validation messages, you’ll need to add the novalidate boolean attribute to your <form>. This disables the browser default feedback tooltips, but still provides access to the form validation APIs in JavaScript. Try to submit the form below; our JavaScript will intercept the submit button and relay feedback to you. When attempting to submit, you’ll see the :invalid and :valid styles applied to your form controls.

    Custom feedback styles apply custom colors, borders, focus styles, and background icons to better communicate feedback. Background icons for <select>s are only available with .form-select, and not .form-control.

    <form class="row g-3 needs-validation" novalidate>
      <div class="col-md-4">
        <label for="validationCustom01" class="form-label">First name</label>
        <input type="text" class="form-control" id="validationCustom01" value="Mark" required>
        <div class="valid-feedback">
          Looks good!
        </div>
      </div>
      <div class="col-md-4">
        <label for="validationCustom02" class="form-label">Last name</label>
        <input type="text" class="form-control" id="validationCustom02" value="Otto" required>
        <div class="valid-feedback">
          Looks good!
        </div>
      </div>
      <div class="col-md-4">
        <label for="validationCustomUsername" class="form-label">Username</label>
        <div class="input-group has-validation">
          <span class="input-group-text" id="inputGroupPrepend">@</span>
          <input type="text" class="form-control" id="validationCustomUsername" aria-describedby="inputGroupPrepend" required>
          <div class="invalid-feedback">
            Please choose a username.
          </div>
        </div>
      </div>
      <div class="col-md-6">
        <label for="validationCustom03" class="form-label">City</label>
        <input type="text" class="form-control" id="validationCustom03" required>
        <div class="invalid-feedback">
          Please provide a valid city.
        </div>
      </div>
      <div class="col-md-3">
        <label for="validationCustom04" class="form-label">State</label>
        <select class="form-select" id="validationCustom04" required>
          <option selected disabled value="">Choose...</option>
          <option>...</option>
        </select>
        <div class="invalid-feedback">
          Please select a valid state.
        </div>
      </div>
      <div class="col-md-3">
        <label for="validationCustom05" class="form-label">Zip</label>
        <input type="text" class="form-control" id="validationCustom05" required>
        <div class="invalid-feedback">
          Please provide a valid zip.
        </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">
            Agree to terms and conditions
          </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 form</button>
      </div>
    </form>
    // Example starter JavaScript for disabling form submissions if there are invalid fields
    (function () {
      'use strict'
    
      // Fetch all the forms we want to apply custom Bootstrap validation styles to
      var forms = document.querySelectorAll('.needs-validation')
    
      // Loop over them and prevent submission
      Array.prototype.slice.call(forms)
        .forEach(function (form) {
          form.addEventListener('submit', function (event) {
            if (!form.checkValidity()) {
              event.preventDefault()
              event.stopPropagation()
            }
    
            form.classList.add('was-validated')
          }, false)
        })
    })()

    Browser defaults

    Not interested in custom validation feedback messages or writing JavaScript to change form behaviors? All good, you can use the browser defaults. Try submitting the form below. Depending on your browser and OS, you’ll see a slightly different style of feedback.

    While these feedback styles cannot be styled with CSS, you can still customize the feedback text through JavaScript.

    <form class="row g-3">
      <div class="col-md-4">
        <label for="validationDefault01" class="form-label">First name</label>
        <input type="text" class="form-control" id="validationDefault01" value="Mark" required>
      </div>
      <div class="col-md-4">
        <label for="validationDefault02" class="form-label">Last name</label>
        <input type="text" class="form-control" id="validationDefault02" value="Otto" required>
      </div>
      <div class="col-md-4">
        <label for="validationDefaultUsername" class="form-label">Username</label>
        <div class="input-group">
          <span class="input-group-text" id="inputGroupPrepend2">@</span>
          <input type="text" class="form-control" id="validationDefaultUsername"  aria-describedby="inputGroupPrepend2" required>
        </div>
      </div>
      <div class="col-md-6">
        <label for="validationDefault03" class="form-label">City</label>
        <input type="text" class="form-control" id="validationDefault03" required>
      </div>
      <div class="col-md-3">
        <label for="validationDefault04" class="form-label">State</label>
        <select class="form-select" id="validationDefault04" required>
          <option selected disabled value="">Choose...</option>
          <option>...</option>
        </select>
      </div>
      <div class="col-md-3">
        <label for="validationDefault05" class="form-label">Zip</label>
        <input type="text" class="form-control" id="validationDefault05" required>
      </div>
      <div class="col-12">
        <div class="form-check">
          <input class="form-check-input" type="checkbox" value="" id="invalidCheck2" required>
          <label class="form-check-label" for="invalidCheck2">
            Agree to terms and conditions
          </label>
        </div>
      </div>
      <div class="col-12">
        <button class="btn btn-primary" type="submit">Submit form</button>
      </div>
    </form>

    Server side

    We recommend using client-side validation, but in case you require server-side validation, you can indicate invalid and valid form fields with .is-invalid and .is-valid. Note that .invalid-feedback is also supported with these classes.

    For invalid fields, ensure that the invalid feedback/error message is associated with the relevant form field using aria-describedby (noting that this attribute allows more than one id to be referenced, in case the field already points to additional form text).

    To fix issues with border radii, input groups require an additional .has-validation class.

    <form class="row g-3">
      <div class="col-md-4">
        <label for="validationServer01" class="form-label">First name</label>
        <input type="text" class="form-control is-valid" id="validationServer01" value="Mark" required>
        <div class="valid-feedback">
          Looks good!
        </div>
      </div>
      <div class="col-md-4">
        <label for="validationServer02" class="form-label">Last name</label>
        <input type="text" class="form-control is-valid" id="validationServer02" value="Otto" required>
        <div class="valid-feedback">
          Looks good!
        </div>
      </div>
      <div class="col-md-4">
        <label for="validationServerUsername" class="form-label">Username</label>
        <div class="input-group has-validation">
          <span class="input-group-text" id="inputGroupPrepend3">@</span>
          <input type="text" class="form-control is-invalid" id="validationServerUsername" aria-describedby="inputGroupPrepend3 validationServerUsernameFeedback" required>
          <div id="validationServerUsernameFeedback" class="invalid-feedback">
            Please choose a username.
          </div>
        </div>
      </div>
      <div class="col-md-6">
        <label for="validationServer03" class="form-label">City</label>
        <input type="text" class="form-control is-invalid" id="validationServer03" aria-describedby="validationServer03Feedback" required>
        <div id="validationServer03Feedback" class="invalid-feedback">
          Please provide a valid city.
        </div>
      </div>
      <div class="col-md-3">
        <label for="validationServer04" class="form-label">State</label>
        <select class="form-select is-invalid" id="validationServer04" aria-describedby="validationServer04Feedback" required>
          <option selected disabled value="">Choose...</option>
          <option>...</option>
        </select>
        <div id="validationServer04Feedback" class="invalid-feedback">
          Please select a valid state.
        </div>
      </div>
      <div class="col-md-3">
        <label for="validationServer05" class="form-label">Zip</label>
        <input type="text" class="form-control is-invalid" id="validationServer05" aria-describedby="validationServer05Feedback" required>
        <div id="validationServer05Feedback" class="invalid-feedback">
          Please provide a valid zip.
        </div>
      </div>
      <div class="col-12">
        <div class="form-check">
          <input class="form-check-input is-invalid" type="checkbox" value="" id="invalidCheck3" aria-describedby="invalidCheck3Feedback" required>
          <label class="form-check-label" for="invalidCheck3">
            Agree to terms and conditions
          </label>
          <div id="invalidCheck3Feedback" class="invalid-feedback">
            You must agree before submitting.
          </div>
        </div>
      </div>
      <div class="col-12">
        <button class="btn btn-primary" type="submit">Submit form</button>
      </div>
    </form>

    Supported elements

    Validation styles are available for the following form controls and components:

    • <input>s and <textarea>s with .form-control (including up to one .form-control in input groups)
    • <select>s with .form-select
    • .form-checks

    Textarea

    Please enter a message in the textarea.

    Check this checkbox

    Example invalid feedback text

    Toggle this radio

    Or toggle this other radio

    More example invalid feedback text

    Example invalid select feedback

    Example invalid form file feedback

    <form class="was-validated">
      <div class="mb-3">
        <label for="validationTextarea" class="form-label">Textarea</label>
        <textarea class="form-control is-invalid" id="validationTextarea" placeholder="Required example textarea" required></textarea>
        <div class="invalid-feedback">
          Please enter a message in the textarea.
        </div>
      </div>
    
      <div class="form-check mb-3">
        <input type="checkbox" class="form-check-input" id="validationFormCheck1" required>
        <label class="form-check-label" for="validationFormCheck1">Check this checkbox</label>
        <div class="invalid-feedback">Example invalid feedback text</div>
      </div>
    
      <div class="form-check">
        <input type="radio" class="form-check-input" id="validationFormCheck2" name="radio-stacked" required>
        <label class="form-check-label" for="validationFormCheck2">Toggle this radio</label>
      </div>
      <div class="form-check mb-3">
        <input type="radio" class="form-check-input" id="validationFormCheck3" name="radio-stacked" required>
        <label class="form-check-label" for="validationFormCheck3">Or toggle this other radio</label>
        <div class="invalid-feedback">More example invalid feedback text</div>
      </div>
    
      <div class="mb-3">
        <select class="form-select" required aria-label="select example">
          <option value="">Open this select menu</option>
          <option value="1">One</option>
          <option value="2">Two</option>
          <option value="3">Three</option>
        </select>
        <div class="invalid-feedback">Example invalid select feedback</div>
      </div>
    
      <div class="mb-3">
        <input type="file" class="form-control" aria-label="file example" required>
        <div class="invalid-feedback">Example invalid form file feedback</div>
      </div>
    
      <div class="mb-3">
        <button class="btn btn-primary" type="submit" disabled>Submit form</button>
      </div>
    </form>

    If your form layout allows it, you can swap the .{valid|invalid}-feedback classes for .{valid|invalid}-tooltip classes to display validation feedback in a styled tooltip. Be sure to have a parent with position: relative on it for tooltip positioning. In the example below, our column classes have this already, but your project may require an alternative setup.

    <form class="row g-3 needs-validation" novalidate>
      <div class="col-md-4 position-relative">
        <label for="validationTooltip01" class="form-label">First name</label>
        <input type="text" class="form-control" id="validationTooltip01" value="Mark" required>
        <div class="valid-tooltip">
          Looks good!
        </div>
      </div>
      <div class="col-md-4 position-relative">
        <label for="validationTooltip02" class="form-label">Last name</label>
        <input type="text" class="form-control" id="validationTooltip02" value="Otto" required>
        <div class="valid-tooltip">
          Looks good!
        </div>
      </div>
      <div class="col-md-4 position-relative">
        <label for="validationTooltipUsername" class="form-label">Username</label>
        <div class="input-group has-validation">
          <span class="input-group-text" id="validationTooltipUsernamePrepend">@</span>
          <input type="text" class="form-control" id="validationTooltipUsername" aria-describedby="validationTooltipUsernamePrepend" required>
          <div class="invalid-tooltip">
            Please choose a unique and valid username.
          </div>
        </div>
      </div>
      <div class="col-md-6 position-relative">
        <label for="validationTooltip03" class="form-label">City</label>
        <input type="text" class="form-control" id="validationTooltip03" required>
        <div class="invalid-tooltip">
          Please provide a valid city.
        </div>
      </div>
      <div class="col-md-3 position-relative">
        <label for="validationTooltip04" class="form-label">State</label>
        <select class="form-select" id="validationTooltip04" required>
          <option selected disabled value="">Choose...</option>
          <option>...</option>
        </select>
        <div class="invalid-tooltip">
          Please select a valid state.
        </div>
      </div>
      <div class="col-md-3 position-relative">
        <label for="validationTooltip05" class="form-label">Zip</label>
        <input type="text" class="form-control" id="validationTooltip05" required>
        <div class="invalid-tooltip">
          Please provide a valid zip.
        </div>
      </div>
      <div class="col-12">
        <button class="btn btn-primary" type="submit">Submit form</button>
      </div>
    </form>

    Sass

    Variables

    $form-feedback-margin-top:          $form-text-margin-top;
    $form-feedback-font-size:           $form-text-font-size;
    $form-feedback-font-style:          $form-text-font-style;
    $form-feedback-valid-color:         $success;
    $form-feedback-invalid-color:       $danger;
    
    $form-feedback-icon-valid-color:    $form-feedback-valid-color;
    $form-feedback-icon-valid:          url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'><path fill='#{$form-feedback-icon-valid-color}' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/></svg>");
    $form-feedback-icon-invalid-color:  $form-feedback-invalid-color;
    $form-feedback-icon-invalid:        url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='#{$form-feedback-icon-invalid-color}'><circle cx='6' cy='6' r='4.5'/><path stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/><circle cx='6' cy='8.2' r='.6' fill='#{$form-feedback-icon-invalid-color}' stroke='none'/></svg>");
    

    Mixins

    Two mixins are combined together, through our loop, to generate our form validation feedback styles.

    @mixin form-validation-state-selector($state) {
      @if ($state == "valid" or $state == "invalid") {
        .was-validated #{if(&, "&", "")}:#{$state},
        #{if(&, "&", "")}.is-#{$state} {
          @content;
        }
      } @else {
        #{if(&, "&", "")}.is-#{$state} {
          @content;
        }
      }
    }
    
    @mixin form-validation-state(
      $state,
      $color,
      $icon,
      $tooltip-color: color-contrast($color),
      $tooltip-bg-color: rgba($color, $form-feedback-tooltip-opacity),
      $focus-box-shadow: 0 0 $input-btn-focus-blur $input-focus-width rgba($color, $input-btn-focus-color-opacity)
    ) {
      .#{$state}-feedback {
        display: none;
        width: 100%;
        margin-top: $form-feedback-margin-top;
        @include font-size($form-feedback-font-size);
        font-style: $form-feedback-font-style;
        color: $color;
      }
    
      .#{$state}-tooltip {
        position: absolute;
        top: 100%;
        z-index: 5;
        display: none;
        max-width: 100%; // Contain to parent when possible
        padding: $form-feedback-tooltip-padding-y $form-feedback-tooltip-padding-x;
        margin-top: .1rem;
        @include font-size($form-feedback-tooltip-font-size);
        line-height: $form-feedback-tooltip-line-height;
        color: $tooltip-color;
        background-color: $tooltip-bg-color;
        @include border-radius($form-feedback-tooltip-border-radius);
      }
    
      @include form-validation-state-selector($state) {
        ~ .#{$state}-feedback,
        ~ .#{$state}-tooltip {
          display: block;
        }
      }
    
      .form-control {
        @include form-validation-state-selector($state) {
          border-color: $color;
    
          @if $enable-validation-icons {
            padding-right: $input-height-inner;
            background-image: escape-svg($icon);
            background-repeat: no-repeat;
            background-position: right $input-height-inner-quarter center;
            background-size: $input-height-inner-half $input-height-inner-half;
          }
    
          &:focus {
            border-color: $color;
            box-shadow: $focus-box-shadow;
          }
        }
      }
    
      // stylelint-disable-next-line selector-no-qualifying-type
      textarea.form-control {
        @include form-validation-state-selector($state) {
          @if $enable-validation-icons {
            padding-right: $input-height-inner;
            background-position: top $input-height-inner-quarter right $input-height-inner-quarter;
          }
        }
      }
    
      .form-select {
        @include form-validation-state-selector($state) {
          border-color: $color;
    
          @if $enable-validation-icons {
            &:not([multiple]):not([size]),
            &:not([multiple])[size="1"] {
              padding-right: $form-select-feedback-icon-padding-end;
              background-image: escape-svg($form-select-indicator), escape-svg($icon);
              background-position: $form-select-bg-position, $form-select-feedback-icon-position;
              background-size: $form-select-bg-size, $form-select-feedback-icon-size;
            }
          }
    
          &:focus {
            border-color: $color;
            box-shadow: $focus-box-shadow;
          }
        }
      }
    
      .form-check-input {
        @include form-validation-state-selector($state) {
          border-color: $color;
    
          &:checked {
            background-color: $color;
          }
    
          &:focus {
            box-shadow: $focus-box-shadow;
          }
    
          ~ .form-check-label {
            color: $color;
          }
        }
      }
      .form-check-inline .form-check-input {
        ~ .#{$state}-feedback {
          margin-left: .5em;
        }
      }
    
      .input-group .form-control,
      .input-group .form-select {
        @include form-validation-state-selector($state) {
          @if $state == "valid" {
            z-index: 1;
          } @else if $state == "invalid" {
            z-index: 2;
          }
          &:focus {
            z-index: 3;
          }
        }
      }
    }
    

    Map

    This is the validation Sass map from _variables.scss. Override or extend this to generate different or additional states.

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

    Maps of $form-validation-states can contain three optional parameters to override tooltips and focus styles.

    Loop

    Used to iterate over $form-validation-states map values to generate our validation styles. Any modifications to the above Sass map will be reflected in your compiled CSS via this loop.

    @each $state, $data in $form-validation-states {
      @include form-validation-state($state, $data...);
    }
    

    Customizing

    Validation states can be customized via Sass with the $form-validation-states map. Located in our _variables.scss file, this Sass map is how we generate the default valid/invalid validation states. Included is a nested map for customizing each state’s color, icon, tooltip color, and focus shadow. While no other states are supported by browsers, those using custom styles can easily add more complex form feedback.

    Please note that we do not recommend customizing $form-validation-states values without also modifying the form-validation-state mixin.

    Нам известно, что в настоящее время пользовательские стили проверки и всплывающие подсказки на стороне клиента недоступны, поскольку они недоступны для вспомогательных технологий. Пока мы работаем над решением, мы рекомендуем использовать либо серверную опцию, либо метод проверки браузера по умолчанию.

    Как это работает

    Вот как валидация форм работает с Bootstrap:

    • Валидация форм HTML работает на 2 псевдоклассах CSS: :invalid и :valid, применяемых к элементам <input>, <select> и <textarea>.
    • Стили этих псевдоклассов применяются к родительскому классу .was-validated, обычно применяемому к <form>. В ином случае любое другое требуемое поле без значения становится невалидным при загрузке страницы. Таким образом можно выбирать, когда активировать формы (обычно после того, как нажато подтверждение).
    • Для сброса внешнего вида формы (например, в случае отправки динамической формы с использованием AJAX) удалите класс .was-validated из <form> после отправки.
    • Как резервный вариант, классы .is-invalid и .is-valid можно использовать вместо псевдоклассов при серверной валидации. Они не требуют родительского класса .was-validated.
    • Благодаря ограничениям, заложенным в самой природе CSS, нельзя (по крайней мере, сегодня) применять стили к элементу <label>, который в DOM расположен перед элементами контроля формы, без использования JavaScript.
    • Все современные браузеры поддерживают API проверки ограничений – серию методов JavaScript для валидации органов контроля форм.
    • В качестве сообщений обратной связи в формах можно использовать таковые по умолчанию браузеров (разные для каждого браузера, и неизменяемые через CSS) или наши стандартные стили сообщений обратной связи с дополнительным HTML и CSS.
    • Вы можете создать сообщения валидации методом setCustomValidity в JavaScript.

    Знаю всё это, посмотрите следующие демонстрации использования стилей валидации форм, серверных классы и настроек браузера по умолчанию.

    Пользовательские стили

    Для стандартных сообщений проверки форм Bootstrap вам потребуется добавить логический атрибут novalidate к <form>. Это деактивирует всплывающие сообщения обратной связи, существующие в браузере по умолчанию, но одновременно сохранит доступ JS к API валидации форм. Попробуйте войти в форму ниже, наш JavaScript выдаст вам сообщение обратной связи. При попытке входа вы увидите, как стили :invalid и :valid применятся к элементам управления формы.

    В пользовательских стилях обратной связи применяются пользовательские цвета, границы, стили фокусировки и значки фона для лучшей передачи обратной связи. Фоновые значки для <select> доступны только с .custom-select, но не с .form-control.

    <form class="row g-3 needs-validation" novalidate>
      <div class="col-md-4">
        <label for="validationCustom01" class="form-label">Имя</label>
        <input type="text" class="form-control" id="validationCustom01" value="Иван" required>
        <div class="valid-feedback">
          Все хорошо!
        </div>
      </div>
      <div class="col-md-4">
        <label for="validationCustom02" class="form-label">Фамилия</label>
        <input type="text" class="form-control" id="validationCustom02" value="Петров" required>
        <div class="valid-feedback">
          Все хорошо!
        </div>
      </div>
      <div class="col-md-4">
        <label for="validationCustomUsername" class="form-label">Имя пользователя</label>
        <div class="input-group has-validation">
          <span class="input-group-text" id="inputGroupPrepend">@</span>
          <input type="text" class="form-control" id="validationCustomUsername" aria-describedby="inputGroupPrepend" required>
          <div class="invalid-feedback">
            Пожалуйста, выберите имя пользователя.
          </div>
        </div>
      </div>
      <div class="col-md-6">
        <label for="validationCustom03" class="form-label">Город</label>
        <input type="text" class="form-control" id="validationCustom03" required>
        <div class="invalid-feedback">
          Укажите действующий город.
        </div>
      </div>
      <div class="col-md-3">
        <label for="validationCustom04" class="form-label">Область</label>
        <select class="form-select" id="validationCustom04" required>
          <option selected disabled value="">Выберите...</option>
          <option>...</option>
        </select>
        <div class="invalid-feedback">
          Пожалуйста, выберите корректный город.
        </div>
      </div>
      <div class="col-md-3">
        <label for="validationCustom05" class="form-label">Индекс</label>
        <input type="text" class="form-control" id="validationCustom05" required>
        <div class="invalid-feedback">
          Пожалуйста, предоставьте действующий почтовый индекс.
        </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">
            Примите условия и соглашения
          </label>
          <div class="invalid-feedback">
            Вы должны принять перед отправкой.
          </div>
        </div>
      </div>
      <div class="col-12">
        <button class="btn btn-primary" type="submit">Отправить форму</button>
      </div>
    </form>
    // Пример стартового JavaScript для отключения отправки форм при наличии недопустимых полей
    (function () {
      'use strict'
    
      // Получите все формы, к которым мы хотим применить пользовательские стили проверки Bootstrap
      var forms = document.querySelectorAll('.needs-validation')
    
      // Зацикливайтесь на них и предотвращайте отправку
      Array.prototype.slice.call(forms)
        .forEach(function (form) {
          form.addEventListener('submit', function (event) {
            if (!form.checkValidity()) {
              event.preventDefault()
              event.stopPropagation()
            }
    
            form.classList.add('was-validated')
          }, false)
        })
    })()
    

    Настройки браузера по умолчанию

    Не нужны стандартные сообщения обратной связи? Не хотите писать скрипты JavaScript для изменения поведения форм? Используйте умолчания браузера. Попробуйте войти в форму ниже. В зависимости от вашего браузера и ОС вы увидите немного разные стили обратной связи.

    Хотя эти сообщения обратной связи нельзя настраивать CSS, их можно настроить с JavaScript.

    <form class="row g-3">
      <div class="col-md-4">
        <label for="validationDefault01" class="form-label">Имя</label>
        <input type="text" class="form-control" id="validationDefault01" value="Иван" required>
      </div>
      <div class="col-md-4">
        <label for="validationDefault02" class="form-label">Фамилия</label>
        <input type="text" class="form-control" id="validationDefault02" value="Петров" required>
      </div>
      <div class="col-md-4">
        <label for="validationDefaultUsername" class="form-label">Имя пользователя</label>
        <div class="input-group">
          <span class="input-group-text" id="inputGroupPrepend2">@</span>
          <input type="text" class="form-control" id="validationDefaultUsername"  aria-describedby="inputGroupPrepend2" required>
        </div>
      </div>
      <div class="col-md-6">
        <label for="validationDefault03" class="form-label">Город</label>
        <input type="text" class="form-control" id="validationDefault03" required>
      </div>
      <div class="col-md-3">
        <label for="validationDefault04" class="form-label">Область</label>
        <select class="form-select" id="validationDefault04" required>
          <option selected disabled value="">Выберите...</option>
          <option>...</option>
        </select>
      </div>
      <div class="col-md-3">
        <label for="validationDefault05" class="form-label">Индекс</label>
        <input type="text" class="form-control" id="validationDefault05" required>
      </div>
      <div class="col-12">
        <div class="form-check">
          <input class="form-check-input" type="checkbox" value="" id="invalidCheck2" required>
          <label class="form-check-label" for="invalidCheck2">
            Примите условия и соглашения
          </label>
        </div>
      </div>
      <div class="col-12">
        <button class="btn btn-primary" type="submit">Отправить форму</button>
      </div>
    </form>

    Проверка на стороне сервера

    Мы рекомендуем использовать валидацию со стороны клиента, но если вам понадобится таковая со стороны сервера, вы можете обозначать валидные и невалидные поля форм классами .is-invalid и .is-valid. Заметим, что их можно также использовать с классом .invalid-feedback.

    Для недопустимых полей убедитесь, что недопустимая обратная связь или сообщение об ошибке связано с соответствующим полем формы с помощью aria-describedby (учитывая, что этот атрибут позволяет ссылаться на несколько id идентификаторов, если поле уже указывает на дополнительный текст формы).

    Чтобы обойти проблему с радиусами границ, необходимо применять дополнительный класс.has-validation.

    <form class="row g-3">
      <div class="col-md-4">
        <label for="validationServer01" class="form-label">Имя</label>
        <input type="text" class="form-control is-valid" id="validationServer01" value="Иван" required>
        <div class="valid-feedback">
          Все хорошо!
        </div>
      </div>
      <div class="col-md-4">
        <label for="validationServer02" class="form-label">Фамилия</label>
        <input type="text" class="form-control is-valid" id="validationServer02" value="Петров" required>
        <div class="valid-feedback">
          Все хорошо!
        </div>
      </div>
      <div class="col-md-4">
        <label for="validationServerUsername" class="form-label">Имя пользователя</label>
        <div class="input-group has-validation">
          <span class="input-group-text" id="inputGroupPrepend3">@</span>
          <input type="text" class="form-control is-invalid" id="validationServerUsername" aria-describedby="inputGroupPrepend3 validationServerUsernameFeedback" required>
          <div id="validationServerUsernameFeedback" class="invalid-feedback">
            Пожалуйста, выберите имя пользователя.
          </div>
        </div>
      </div>
      <div class="col-md-6">
        <label for="validationServer03" class="form-label">Город</label>
        <input type="text" class="form-control is-invalid" id="validationServer03" aria-describedby="validationServer03Feedback" required>
        <div id="validationServer03Feedback" class="invalid-feedback">
          Укажите действующий город.
        </div>
      </div>
      <div class="col-md-3">
        <label for="validationServer04" class="form-label">Область</label>
        <select class="form-select is-invalid" id="validationServer04" aria-describedby="validationServer04Feedback" required>
          <option selected disabled value="">Выберите...</option>
          <option>...</option>
        </select>
        <div id="validationServer04Feedback" class="invalid-feedback">
          Пожалуйста, выберите корректный город.
        </div>
      </div>
      <div class="col-md-3">
        <label for="validationServer05" class="form-label">Индекс</label>
        <input type="text" class="form-control is-invalid" id="validationServer05" aria-describedby="validationServer05Feedback" required>
        <div id="validationServer05Feedback" class="invalid-feedback">
          Пожалуйста, предоставьте действующий почтовый индекс.
        </div>
      </div>
      <div class="col-12">
        <div class="form-check">
          <input class="form-check-input is-invalid" type="checkbox" value="" id="invalidCheck3" aria-describedby="invalidCheck3Feedback" required>
          <label class="form-check-label" for="invalidCheck3">
            Примите условия и соглашения
          </label>
          <div id="invalidCheck3Feedback" class="invalid-feedback">
            Вы должны принять перед отправкой.
          </div>
        </div>
      </div>
      <div class="col-12">
        <button class="btn btn-primary" type="submit">Отправить форму</button>
      </div>
    </form>

    Поддерживаемые элементы

    Стили проверки доступны для следующих элементов управления формы и компонентов:

    • <input> и <textarea> с .form-control (включая до одного .form-control в группах ввода)
    • <select> с .form-select
    • .form-check

    Текстовое поле

    Пожалуйста, введите сообщение в текстовое поле.

    Отметьте этот флажок

    Пример неверного текста обратной связи

    Переключить это радио

    Или переключить это другое радио

    Еще пример неверного текста обратной связи

    Пример обратной связи неверного выбора

    Пример обратной связи неверной формы выбора файла

    <form class="was-validated">
      <div class="mb-3">
        <label for="validationTextarea" class="form-label">Текстовое поле</label>
        <textarea class="form-control is-invalid" id="validationTextarea" placeholder="Обязательный пример текстового поля" required></textarea>
        <div class="invalid-feedback">
          Пожалуйста, введите сообщение в текстовое поле.
        </div>
      </div>
    
      <div class="form-check mb-3">
        <input type="checkbox" class="form-check-input" id="validationFormCheck1" required>
        <label class="form-check-label" for="validationFormCheck1">Отметьте этот флажок</label>
        <div class="invalid-feedback">Пример неверного текста обратной связи</div>
      </div>
    
      <div class="form-check">
        <input type="radio" class="form-check-input" id="validationFormCheck2" name="radio-stacked" required>
        <label class="form-check-label" for="validationFormCheck2">Переключить это радио</label>
      </div>
      <div class="form-check mb-3">
        <input type="radio" class="form-check-input" id="validationFormCheck3" name="radio-stacked" required>
        <label class="form-check-label" for="validationFormCheck3">Или переключить это другое радио</label>
        <div class="invalid-feedback">Еще пример неверного текста обратной связи</div>
      </div>
    
      <div class="mb-3">
        <select class="form-select" required aria-label="select example">
          <option value="">Откройте это меню выбора</option>
          <option value="1">Один</option>
          <option value="2">Два</option>
          <option value="3">Три</option>
        </select>
        <div class="invalid-feedback">Пример обратной связи неверного выбора </div>
      </div>
    
      <div class="mb-3">
        <input type="file" class="form-control" aria-label="file example" required>
        <div class="invalid-feedback">Пример обратной связи неверной формы выбора файла</div>
      </div>
    
      <div class="mb-3">
        <button class="btn btn-primary" type="submit" disabled>Отправить форму</button>
      </div>
    </form>

    Если разметка ваших форм позволит, вы можете заменить классы .{valid|invalid}-feedback классами .{valid|invalid}-tooltip — для отображения обратной связи валидации, стилизованной под всплывающую подсказку. Для правильного позиционирования всплывающей подсказки удостоверьтесь, что родительский элемент содержит position: relative. В примере ниже наши классы колонок уже имеют этот атрибут, но ваш проект может потребовать иные настройки.

    <form class="row g-3 needs-validation" novalidate>
      <div class="col-md-4 position-relative">
        <label for="validationTooltip01" class="form-label">Имя</label>
        <input type="text" class="form-control" id="validationTooltip01" value="Иван" required>
        <div class="valid-tooltip">
          Все хорошо!
        </div>
      </div>
      <div class="col-md-4 position-relative">
        <label for="validationTooltip02" class="form-label">Фамилия</label>
        <input type="text" class="form-control" id="validationTooltip02" value="Петров" required>
        <div class="valid-tooltip">
          Все хорошо!
        </div>
      </div>
      <div class="col-md-4 position-relative">
        <label for="validationTooltipUsername" class="form-label">Имя пользователя</label>
        <div class="input-group has-validation">
          <span class="input-group-text" id="validationTooltipUsernamePrepend">@</span>
          <input type="text" class="form-control" id="validationTooltipUsername" aria-describedby="validationTooltipUsernamePrepend" required>
          <div class="invalid-tooltip">
            Пожалуйста, выберите уникальное и действительное имя пользователя.
          </div>
        </div>
      </div>
      <div class="col-md-6 position-relative">
        <label for="validationTooltip03" class="form-label">Город</label>
        <input type="text" class="form-control" id="validationTooltip03" required>
        <div class="invalid-tooltip">
          Укажите действующий город.
        </div>
      </div>
      <div class="col-md-3 position-relative">
        <label for="validationTooltip04" class="form-label">Область</label>
        <select class="form-select" id="validationTooltip04" required>
          <option selected disabled value="">Выберите...</option>
          <option>...</option>
        </select>
        <div class="invalid-tooltip">
          Пожалуйста, выберите корректный город.
        </div>
      </div>
      <div class="col-md-3 position-relative">
        <label for="validationTooltip05" class="form-label">Индекс</label>
        <input type="text" class="form-control" id="validationTooltip05" required>
        <div class="invalid-tooltip">
          Пожалуйста, предоставьте действующий почтовый индекс.
        </div>
      </div>
      <div class="col-12">
        <button class="btn btn-primary" type="submit">Отправить форму</button>
      </div>
    </form>

    Sass

    Переменные

    $form-feedback-margin-top:          $form-text-margin-top;
    $form-feedback-font-size:           $form-text-font-size;
    $form-feedback-font-style:          $form-text-font-style;
    $form-feedback-valid-color:         $success;
    $form-feedback-invalid-color:       $danger;
    
    $form-feedback-icon-valid-color:    $form-feedback-valid-color;
    $form-feedback-icon-valid:          url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'><path fill='#{$form-feedback-icon-valid-color}' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/></svg>");
    $form-feedback-icon-invalid-color:  $form-feedback-invalid-color;
    $form-feedback-icon-invalid:        url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='#{$form-feedback-icon-invalid-color}'><circle cx='6' cy='6' r='4.5'/><path stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/><circle cx='6' cy='8.2' r='.6' fill='#{$form-feedback-icon-invalid-color}' stroke='none'/></svg>");
    

    Миксины

    Два миксина объединяются вместе с помощью нашего цикла, чтобы сгенерировать наши стили обратной связи для проверки формы.

    @mixin form-validation-state-selector($state) {
      @if ($state == "valid" or $state == "invalid") {
        .was-validated #{if(&, "&", "")}:#{$state},
        #{if(&, "&", "")}.is-#{$state} {
          @content;
        }
      } @else {
        #{if(&, "&", "")}.is-#{$state} {
          @content;
        }
      }
    }
    
    @mixin form-validation-state(
      $state,
      $color,
      $icon,
      $tooltip-color: color-contrast($color),
      $tooltip-bg-color: rgba($color, $form-feedback-tooltip-opacity),
      $focus-box-shadow: 0 0 $input-btn-focus-blur $input-focus-width rgba($color, $input-btn-focus-color-opacity)
    ) {
      .#{$state}-feedback {
        display: none;
        width: 100%;
        margin-top: $form-feedback-margin-top;
        @include font-size($form-feedback-font-size);
        font-style: $form-feedback-font-style;
        color: $color;
      }
    
      .#{$state}-tooltip {
        position: absolute;
        top: 100%;
        z-index: 5;
        display: none;
        max-width: 100%; // Contain to parent when possible
        padding: $form-feedback-tooltip-padding-y $form-feedback-tooltip-padding-x;
        margin-top: .1rem;
        @include font-size($form-feedback-tooltip-font-size);
        line-height: $form-feedback-tooltip-line-height;
        color: $tooltip-color;
        background-color: $tooltip-bg-color;
        @include border-radius($form-feedback-tooltip-border-radius);
      }
    
      @include form-validation-state-selector($state) {
        ~ .#{$state}-feedback,
        ~ .#{$state}-tooltip {
          display: block;
        }
      }
    
      .form-control {
        @include form-validation-state-selector($state) {
          border-color: $color;
    
          @if $enable-validation-icons {
            padding-right: $input-height-inner;
            background-image: escape-svg($icon);
            background-repeat: no-repeat;
            background-position: right $input-height-inner-quarter center;
            background-size: $input-height-inner-half $input-height-inner-half;
          }
    
          &:focus {
            border-color: $color;
            box-shadow: $focus-box-shadow;
          }
        }
      }
    
      // stylelint-disable-next-line selector-no-qualifying-type
      textarea.form-control {
        @include form-validation-state-selector($state) {
          @if $enable-validation-icons {
            padding-right: $input-height-inner;
            background-position: top $input-height-inner-quarter right $input-height-inner-quarter;
          }
        }
      }
    
      .form-select {
        @include form-validation-state-selector($state) {
          border-color: $color;
    
          @if $enable-validation-icons {
            &:not([multiple]):not([size]),
            &:not([multiple])[size="1"] {
              padding-right: $form-select-feedback-icon-padding-end;
              background-image: escape-svg($form-select-indicator), escape-svg($icon);
              background-position: $form-select-bg-position, $form-select-feedback-icon-position;
              background-size: $form-select-bg-size, $form-select-feedback-icon-size;
            }
          }
    
          &:focus {
            border-color: $color;
            box-shadow: $focus-box-shadow;
          }
        }
      }
    
      .form-check-input {
        @include form-validation-state-selector($state) {
          border-color: $color;
    
          &:checked {
            background-color: $color;
          }
    
          &:focus {
            box-shadow: $focus-box-shadow;
          }
    
          ~ .form-check-label {
            color: $color;
          }
        }
      }
      .form-check-inline .form-check-input {
        ~ .#{$state}-feedback {
          margin-left: .5em;
        }
      }
    
      .input-group .form-control,
      .input-group .form-select {
        @include form-validation-state-selector($state) {
          @if $state == "valid" {
            z-index: 1;
          } @else if $state == "invalid" {
            z-index: 2;
          }
          &:focus {
            z-index: 3;
          }
        }
      }
    }
    

    Карта

    Это карта валидации Sass из _variables.scss. Переопределите или расширьте это, чтобы создать другие или дополнительные состояния.

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

    Карты $form-validation-states могут содержать три необязательных параметра для переопределения всплывающих подсказок и стилей фокуса.

    Цикл

    Используется для перебора значений карты $form-validation-states для генерации наших стилей проверки. Любые изменения в приведенной выше карте Sass будут отражены в Вашем скомпилированном CSS через этот цикл.

    @each $state, $data in $form-validation-states {
      @include form-validation-state($state, $data...);
    }
    

    Пользовательские настройки

    Состояния проверки можно настроить через Sass с помощью карты $form-validation-states. Эта карта Sass, расположенная в нашем файле _variables.scss, используется для генерации состояний валидации по умолчанию valid/invalid. ключена вложенная карта для настройки цвета каждого состояния, значка, цвета всплывающей подсказки и тени фокуса. Хотя браузеры не поддерживают никакие другие состояния, те, кто использует собственные стили, могут легко добавить более сложную обратную связь с формой.

    Обратите внимание, что мы не рекомендуем настраивать значения $form-validation-states без изменения миксина form-validation-state.

    Recently, when writing code for my blog post on drop downs, “DropDownListFor with Dictionaries in
    ASP.NET MVC and why SelectList wants to kill you”, I stumbled over an interesting problem –
    when using ASP.NET MVC HTML helpers, such as @Html.TextBoxFor() and @Html.DropDownListFor() to
    render controls and @Html.ValidationMessageFor() to render validation error messages, I realised
    that ASP.NET MVC uses its own CSS classes, so no errors are getting highlighted when using Bootstrap
    3.

    There’s nothing wrong with MVC as such in here, as it is meant to be CSS framework agnostic, meaning
    you should be able to use it with any CSS framework.

    Problem

    To get a better understanding of the problem, have a look at this HTML that’s generated by MVC on
    postback. It contains an error message for a required text field.

    <div class="form-group">
    
        <label for="FirstName">First name</label>
    
        <input class="input-validation-error form-control" data-val="true"
               data-val-required="The First name field is required."
               id="FirstName" name="FirstName" type="text" value="">
    
        <span class="field-validation-error" data-valmsg-for="FirstName"
              data-valmsg-replace="true">The First name field is required.</span>
    </div>

    As you can see, ASP.NET uses its own CSS classes, such as input-validation-error (used to
    highlight control with an invalid value) and field-validation-error which contains explanatory
    text for the error.

    Without proper styling the above HTML looks like this:

    No styling on the control

    Not too bad, but could be better. Bootstrap 3 has this awesome indication for invalid form controls,
    and it highlights the entire control and the error text:

    Like a boss

    So following Bootstrap’s own documentation we need to make sure that control with error has a
    parent with the class of has-error and the validation error message element needs to have the
    class of text-danger. That’s how HTML needs to look like to get proper error highlighting:

    <div class="has-error form-group"> <!-- 'has-error' class has been added on parent form-group div -->
    
        <label for="FirstName">First name</label>
    
        <input class="input-validation-error form-control" data-val="true"
               data-val-required="The First name field is required."
               id="FirstName" name="FirstName" type="text" value="">
    
        <!-- 'text-danger' has been added on the span with validation error message -->
        <span class="text-danger field-validation-error" data-valmsg-for="FirstName"
              data-valmsg-replace="true">The First name field is required.</span>
    </div>

    Solution

    It is clear that we just need to add two puny CSS classes, but how exactly this is done depends on
    whether you use client-side JavaScript validation or not.

    No client-side validation

    If your form is submitted to the server with no prior on-the-client JavaScript validation (old
    school! but it works), then you’ve got yourself the easiest of all fixed. You can just add these CSS
    classes whenever the page loads in the following fashion:

    $(document).ready(function() {
        $('.input-validation-error').parents('.form-group').addClass('has-error');
        $('.field-validation-error').addClass('text-danger');
    });

    ASP.NET MVC Unobtrusive validation

    Most likely though you’re using in-built ASP.NET MVC’s own unobtrusive jQuery validation, in
    which case we need to hook into success and errorPlacement events of the jQuery Validation
    Plugin:

    $(document).ready(function () {
        var form = $('#userForm')
            , formData = $.data(form[0])
            , settings = formData.validator.settings
            // Store existing event handlers in local variables
            , oldErrorPlacement = settings.errorPlacement
            , oldSuccess = settings.success;
    
        settings.errorPlacement = function(label, element) {
    
            // Call old handler so it can update the HTML
            oldErrorPlacement(label, element);
    
            // Add Bootstrap classes to newly added elements
            label.parents('.form-group').addClass('has-error');
            label.addClass('text-danger');
        };
    
        settings.success = function(label) {
            // Remove error class from <div class="form-group">, but don't worry about
            // validation error messages as the plugin is going to remove it anyway
            label.parents('.form-group').removeClass('has-error');
    
            // Call old handler to do rest of the work
            oldSuccess(label);
        };
    });

    Now admittedly this is a tad hacky, I personally don’t like how our validation code assumes a number
    of dangerous things, such as knowledge of parameter lists for internal functions, but it works.

    Fluent Validation

    FluentValidation is another popular library for ASP.NET MVC, and given it integrates with
    standard validation, you can use solutions listed above to make it work.

    Get complete, tested, and working source code for this article

    Download fully tested and 100% working Visual Studio solution with the source
    code used in this article for FREE – just enter your name and email in the
    form below, and I’ll send you the download link right away.

    You will also get access to all the source code for all existing and new
    articles on the site, and access to my mailing list, which receives handy
    timesaving tips on .NET Core programming.

    Subscribe now and get helpful tips on developing .NET apps — never miss a new article.

    Copyright © Art Skvira. Some rights reserved.

    Suggested Video Tutorials
    Part 20 — Bootstrap forms
    Part 21 — Bootstrap form controls

    Part 22 — Bootstrap disabled and readonly form controls

    In this video, we will discuss the bootstrap classes that can be used to style the form controls based on their validation state.

    The following are the boostrap classes and glyphicons that can be used to style the form controls depending on the validation state i.e success, warning or error

    Class Glyphicon Purpose
    has-success glyphicon glyphicon-ok Success Validation State
    has-warning glyphicon glyphicon-warning-sign Warning Validation State
    has-error glyphicon glyphicon-remove Error Validation State

    The following example, styles the form controls depending on their validation state. The bootstrap validation classes (has-success, has-warning & has-error) are being used on the parent <div> element. We are also using help-block class to display the help text associated with the form control.

    bootstrap form validation example

    <form class=»form-horizontal»>

        <div class=»form-group
    has-success»>

            <label class=»col-xs-2
    control-label»
    for=»txtStrongPassword»>Password</label>

            <div class=»col-xs-10″>

                <input type=»password» id=»txtStrongPassword» class=»form-control»

                        placeholder=»Your
    password»>

                <span class=»help-block»>Strong Password</span>

            </div>

        </div>

        <div class=»form-group
    has-warning»>

            <label class=»col-xs-2
    control-label»
    for=»txtWeakPassword»>Password</label>

            <div class=»col-xs-10″>

                <input type=»password» id=»txtWeakPassword» class=»form-control»

                        placeholder=»Your
    password»>

                <span class=»help-block»>Weak Password</span>

            </div>

        </div>

        <div class=»form-group
    has-error»>

            <label class=»col-xs-2
    control-label»
    for=»txtAge»>Age</label>

            <div class=»col-xs-10″>

                <input type=»number» id=»txtAge» class=»form-control»

                        placeholder=»Your
    Age»>

                <span class=»help-block»>Invalid Age</span>

            </div>

        </div>



    In the following example, we are also displaying the validation icons depending on the validation state of the control. To use icons we also have to use has-feedback and form-control-feedback classes. Please note that Icons only work with textual <input> elements

    bootstrap 3 form validation icons

    <form class=»form-horizontal»>

        <div class=»form-group
    has-success has-feedback»>

            <label class=»col-xs-2
    control-label»
    for=»txtStrongPassword»>Password</label>

            <div class=»col-xs-10″>

                <input type=»password» id=»txtStrongPassword» class=»form-control»

                        placeholder=»Your
    password»>

                <span class=»glyphicon
    glyphicon-ok form-control-feedback»></
    span>

                <span class=»help-block»>Strong Password</span>

            </div>

        </div>

        <div class=»form-group
    has-warning has-feedback»>

            <label class=»col-xs-2
    control-label»
    for=»txtWeakPassword»>Password</label>

            <div class=»col-xs-10″>

                <input type=»password» id=»txtWeakPassword» class=»form-control»

                        placeholder=»Your
    password»>

                <span class=»glyphicon
    glyphicon-warning-sign form-control-feedback»></
    span>

                <span class=»help-block»>Weak Password</span>

            </div>

        </div>

        <div class=»form-group
    has-error has-feedback»>

            <label class=»col-xs-2
    control-label»
    for=»txtAge»>Age</label>

            <div class=»col-xs-10″>

                <input type=»number» id=»txtAge» class=»form-control»

                        placeholder=»Your
    Age»>

                <span class=»glyphicon
    glyphicon-remove form-control-feedback»></
    span>

                <span class=»help-block»>Invalid Age</span>

            </div>

        </div>



    The following example, styles the input groups depending on their validation state. As you can see, styling input groups is similar to styling regular form controls.

    bootstrap input group addon validation

    <form class=»form-horizontal»>

        <div class=»form-group
    has-success has-feedback»>

            <label class=»col-xs-2
    control-label»
    for=»txtStrongPassword»>Income</label>

            <div class=»col-xs-10″>

                <div class=»input-group»>

                    <span class=»input-group-addon»>$</span>

                    <input type=»text» id=»txtIncome» class=»form-control»

                            placeholder=»Your
    annual income after taxes»>

                </div>

                <span class=»glyphicon
    glyphicon-ok form-control-feedback»></
    span>

                <span class=»help-block»>Success</span>

            </div>

        </div>

        <div class=»form-group
    has-warning has-feedback»>

            <label class=»col-xs-2
    control-label»
    for=»txtStrongPassword»>Income</label>

            <div class=»col-xs-10″>

                <div class=»input-group»>

                    <span class=»input-group-addon»>$</span>

                    <input type=»text» id=»txtIncome» class=»form-control»

                            placeholder=»Your
    annual income after taxes»>

                </div>

                <span class=»glyphicon
    glyphicon-warning-sign form-control-feedback»></
    span>

                <span class=»help-block»>Warning</span>

            </div>

        </div>

        <div class=»form-group
    has-error has-feedback»>

            <label class=»col-xs-2
    control-label»
    for=»txtStrongPassword»>Income</label>

            <div class=»col-xs-10″>

                <div class=»input-group»>

                    <span class=»input-group-addon»>$</span>

                    <input type=»text» id=»txtIncome» class=»form-control»

                            placeholder=»Your
    annual income after taxes»>

                </div>

                <span class=»glyphicon
    glyphicon-remove form-control-feedback»></
    span>

                <span class=»help-block»>Error</span>

            </div>

        </div>

    bootstrap tutorial for beginners

    BootstrapMarch 10, 2021 • 7 minutes READ

    Form validation is one of the most critical factors when it comes to collecting information and preventing web form misuse.

    Apart from saving you from possible cyber-attacks, form validation also protects your website from poor form entries. During form submission with validation, the user will be given the option to modify data fields that contain invalid data before submitting.

    In general, you need form validation as a security measure since invalidated form data is one of the main sources of website security vulnerabilities.

    Forms are fully supported in Bootstrap 5. Most of the components are mainly used to make the forms look clean and responsive which can be used with any screen size. While Bootstrap 5 forms automatically receive the correct formatting via given classes, when it comes to form validation you need to set up some extra classes and some JavaScript in order to take advantage of its contemporary validation support right out of the box.

    In this article, I will show you how you can use Bootstrap 5 form validation to showcase some decent actionable feedback on form data fields such as textbox, select, checkbox, radio button along with some other available bootstrap’s form fields upon form submission. We will use JavaScript to disable form submissions if there are invalid fields entered.

    Note: HTML 5 has its own validation means, but it has limitations especially when it comes to browser support. One of the noticeable limitations is the lack of customization when it comes to handling error messages which you will need to find a way to get sorted. Fortunately, Bootstrap 5 has contemporary form validation styles at hand.

    Online Email Template Builder

    With Postcards you can create and edit email templates online without any coding skills! Includes more than 100 components to help you create custom emails templates faster than ever before.

    Try FreeOther Products

    How it Works

    Bootstrap 5 comes with super easy to use, yet powerful validation styles for input fields. These validation styles are used to showcase some form styles and messages, both errors and success states for form fields, and can be triggered when you submit the actual form.

    Supported HTML Elements

    Bootstrap 5 validation styles can be used on the following HTML elements including up to one .form-control class in input groups.

    • <input>
    • <select>
    • <textarea>

    For the input element, you can use Bootstrap 5 validation styles on commonly used tags such as textbox, radio button, checkbox, and file element tag.

    Bootstrap 5 form validation basically has two states: error and success. These are represented by the following semantic classes.

    • .is-invalid: Error
    • .is-valid: Success

    Let’s take a look at the code to render these two validation states:

    <div class="col-md-4">
       <label for="validationSuccess" class="form-label text-success">Input with success</label>
       <input type="text" class="form-control is-valid" id="validationSuccess" required>
    </div>
    <div class="col-md-4">
       <label for="validationError" class="form-label text-danger">Input with error</label>
       <input type="text" class="form-control is-invalid" id="validationError" required>
    </div>
    

    The markup that you see above is very similar to usual inputs with the addition of a few CSS classes to apply the proper state look and feel.

    Let’s go over code you need to be aware of:

    • The first input is the success state. The input field needs to have a class called .is-valid added to it.
    • The second input is the error state. The input field needs to have a class called .is-invalid added to it.
    • Notice each input has an icon to the right edge of it. These icons are automatically added when you include the required bootstrap CSS files.
    • Each <label> tag has a class .text-success and .text-danger added to it. These are not required in form validation but these are for demonstration purposes only to color the label to match the state color.

    Let’s take a look at how these validation inputs should look in the browser:

    How to Validate Forms with Bootstrap 5

    Next, let’s see how form validation messages work with Bootstrap 5 form validation at a very basic level. Bootstrap 5 form validation also provides two states for form validation messages similar to input validation above: error and success.

    These are represented by the following semantic classes.

    • .invalid-feedback: Error
    • .valid-feedback: Success

    Let’s take a look at the code to render these two validation messages states:

    <div class="col-md-4">
       <label for="validationSuccess" class="form-label text-success">Input with success</label>
       <input type="text" class="form-control is-valid" id="validationSuccess" required>
       <div class="valid-feedback">
          This is a success state form validation message!
       </div>
    </div>
    <div class="col-md-4">
    <label for="validationError" class="form-label text-danger">Input with error</label>
    <input type="text" class="form-control is-invalid" id="validationError" required>
    <div class="invalid-feedback">
       This is an error state form validation message!
    </div>
    

    Let’s go over code you need to be aware of:

    • The div with a class .valid-feedback is the form validation message success.
    • The div with a class .invalid-feedback is the form validation message error.
    • Each class stated above needs to be used together below the input field and then bootstrap with the help of JavaScript will determine which one to show based on user entry upon form submission. More on this later.

    Let’s take a look at how these validation inputs should look in the browser:

    Bootstrap Form Validation

    As seen above, the inputs and form validation messages are colored to match their state. Additionally, notice that we used .is-valid and .is-invalid to match the state for a particular validation.

    However, with Bootstrap along with the use of JavaScript upon form submission, you don’t need to imperatively put these two classes on each data field. Bootstrap will handle it for you accordingly. Bootstrap form validation is applied using CSS’s two pseudo-classes, :valid and:invalid. Bootstrap out looked these classes’ styles which is usually applied with the use of .was-validated class in the <form> tag. The .is-valid and .is-invalid classes may still be used instead of the pseudo-classes for server-side validation. Please take note that if you will use these classes on server-side validation you don’t need to add .was-validated class.

    Validation Style Using Tooltips

    Bootstrap also comes with tooltip styles for its contemporary validation styles. Tooltip or infotip is a common user interface element where in hovering over an element, a pop up box displays the required information for that specific element but in this case, it would be the validation message.

    For the tooltip validation feature to work you need to use .valid-tooltip or .invalid-tooltip class to match the state for a particular validation style and form validation message instead of using .valid-feedback and .invalid-feedback. Additionally, you need to have a parent element with position: relative style for tooltip positioning.

    The code below is identical to the code above but this time using tooltip as it’s contemporary validation style.

    <div class="col-md-4 position-relative">
       <label for="validationSuccess" class="form-label text-success">Input with success</label>
       <input type="text" class="form-control" value="Samuel Norton" required>
       <div class="valid-tooltip">
          This is a success state form validation message!
       </div>
    </div>
    <div class="col-md-4 position-relative">
       <label for="validationError" class="form-label text-danger">Input with error</label>
       <input type="text" class="form-control" id="validationError" required>
       <div class="invalid-tooltip">
          This is an error state form validation message!
       </div>
    </div>
    

    Let’s take a look at how these validation inputs should look in the browser:

    JavaScript Validation

    Using JavaScript

    Now let’s see how JavaScript can help our bootstrap validation styles prevent any invalid submissions from the users.

    First, take a look at the following markup:

    <form class="row g-3 requires-validation" novalidate>
       <div class="col-md-12">
          <label for="username" class="form-label">Username:</label>
          <input type="text" class="form-control" id="username" required>
          <div class="valid-feedback">
             Username looks good!
          </div>
          <div class="invalid-feedback">
             Username is required!
          </div>
       </div>
       <div class="col-md-12">
          <label for="password" class="form-label">Password:</label>
          <input type="text" class="form-control" id="password" required>
          <div class="valid-feedback">
             Password looks good!
          </div>
          <div class="invalid-feedback">
             Password is required!
          </div>
       </div>
       <div class="col-12">
          <button class="btn btn-primary" type="submit">Login</button>
       </div>
    </form>
    

    Let’s take a look closer at the markup above:

    • The form tag has a novalidate boolean attribute. This prevents the browser default feedback tooltips without the occlusion of access to the form validation APIs in JavaScript.
    • We did not include the .is-valid and .is-invalid classes on each data field. Bootstrap’s :invalid and :valid styles will apply it to the form controls with the use of JavaScript.
    • We added a .requires-validation class inside the form tag. This is not a semantic class from bootstrap. You can rename it to whatever class name you prefer. The purpose of this class is to help JavaScript fetch all the form elements to apply custom bootstrap validation styles accordingly (more on this later).
    • On each data field or inputs, we added the required attribute at the end. This simply states that a particular data field must be filled out before submitting the form.
    • Again, we use .valid-feedback and .invalid-feedback at the bottom of each data field. The div with a class .valid-feedback is the form validation message success Wherein, the div with a class .invalid-feedback is the form validation message error state.

    Next, let’s add the JavaScript code to disable form submissions if there are invalid fields when the user submits the form:

    <script>
    (function () {
    'use strict'
    const forms = document.querySelectorAll('.requires-validation')
    Array.from(forms)
      .forEach(function (form) {
        form.addEventListener('submit', function (event) {
      	if (!form.checkValidity()) {
            event.preventDefault()
            event.stopPropagation()
      	}
     
          form.classList.add('was-validated')
    	}, false)
      })
    })()
    </script>
    

    The JavaScript code above simply gets all forms via querySelectorAll method and returns a static NodeList which represents a list of the document’s elements using the .requires-validation class.

    Next, for each one of the forms found, the JavaScript code will add an EventListener that will be called whenever the specified event is delivered and that is submitted. So whenever a user submits the form, form.checkValidity() will be called out. This method verifies whether the data field has any constraints and fulfills the given constraints. If it fails, the browser simply fires an invalid event and returns false.

    So if it fails, it will call both of the following JavaScript methods:

    • preventDefault() – a method that will simply prevent the default event to be taken as it normally would be. In this case the submission of the form.
    • stopPropagation() – a method that prevents further propagation (bubbling up) of the current event.

    Finally, it will add .was-validated class in the form tag to show the form validation state and messages.

    Bootstrap scopes the :invalid and :valid styles to parent .was-validated class when it is applied to the form. You can actually put the .was-validated class to the form tag even without the help of JavaScript but that will automatically show the form validation states and messages even before the user submits the form. However, having JavaScript to take care of the form submission and validation event will give you a more secure contemporary validation process on the client-side.

    Let’s take a look at how this should look in the browser:

    JavaScript code

    Putting It All Together

    Now to put this all together, let’s create a simple registration page and see how we can apply Bootstrap 5 contemporary validation styles on each data field.

    Below is the markup.

    <div class="form-body">
       <div class="row">
          <div class="form-holder">
             <div class="form-content">
                <div class="form-items">
                   <h3>Register Today</h3>
                   <p>Fill in the data below.</p>
                   <form class="requires-validation" novalidate>
                      <div class="col-md-12">
                         <input class="form-control" type="text" name="name" placeholder="Full Name" required>
                         <div class="valid-feedback">Username field is valid!</div>
                         <div class="invalid-feedback">Username field cannot be blank!</div>
                      </div>
                      <div class="col-md-12">
                         <input class="form-control" type="email" name="email" placeholder="E-mail Address" required>
                         <div class="valid-feedback">Email field is valid!</div>
                         <div class="invalid-feedback">Email field cannot be blank!</div>
                      </div>
                      <div class="col-md-12">
                         <select class="form-select mt-3" required>
                            <option selected disabled value="">Position</option>
                            <option value="jweb">Junior Web Developer</option>
                            <option value="sweb">Senior Web Developer</option>
                            <option value="pmanager">Project Manager</option>
                         </select>
                         <div class="valid-feedback">You selected a position!</div>
                         <div class="invalid-feedback">Please select a position!</div>
                      </div>
                      <div class="col-md-12">
                         <input class="form-control" type="password" name="password" placeholder="Password" required>
                         <div class="valid-feedback">Password field is valid!</div>
                         <div class="invalid-feedback">Password field cannot be blank!</div>
                      </div>
                      <div class="col-md-12 mt-3">
                         <label class="mb-3 mr-1" for="gender">Gender: </label>
                         <input type="radio" class="btn-check" name="gender" id="male" autocomplete="off" required>
                         <label class="btn btn-sm btn-outline-secondary" for="male">Male</label>
                         <input type="radio" class="btn-check" name="gender" id="female" autocomplete="off" required>
                         <label class="btn btn-sm btn-outline-secondary" for="female">Female</label>
                         <input type="radio" class="btn-check" name="gender" id="secret" autocomplete="off" required>
                         <label class="btn btn-sm btn-outline-secondary" for="secret">Secret</label>
                         <div class="valid-feedback mv-up">You selected a gender!</div>
                         <div class="invalid-feedback mv-up">Please select a gender!</div>
                      </div>
                      <div class="form-check">
                         <input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
                         <label class="form-check-label">I confirm that all data are correct</label>
                         <div class="invalid-feedback">Please confirm that the entered data are all correct!</div>
                      </div>
                      <div class="form-button mt-3">
                         <button id="submit" type="submit" class="btn btn-primary">Register</button>
                      </div>
                   </form>
                </div>
             </div>
          </div>
       </div>
    </div>
    

    Next, I’ve added CSS to customize the look and feel of our form.

    @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;700;900&display=swap');
    *,
    body {
    	font-family: 'Poppins', sans-serif;
    	font-weight: 400;
    	-webkit-font-smoothing: antialiased;
    	text-rendering: optimizeLegibility;
    	-moz-osx-font-smoothing: grayscale;
    }
    
    html,
    body {
    	height: 100%;
    	background-color: #152733;
    	overflow: hidden;
    }
    
    .form-holder {
    	display: flex;
    	flex-direction: column;
    	justify-content: center;
    	align-items: center;
    	text-align: center;
    	min-height: 100vh;
    }
    
    .form-holder .form-content {
    	position: relative;
    	text-align: center;
    	display: -webkit-box;
    	display: -moz-box;
    	display: -ms-flexbox;
    	display: -webkit-flex;
    	display: flex;
    	-webkit-justify-content: center;
    	justify-content: center;
    	-webkit-align-items: center;
    	align-items: center;
    	padding: 60px;
    }
    
    .form-content .form-items {
    	border: 3px solid #fff;
    	padding: 40px;
    	display: inline-block;
    	width: 100%;
    	min-width: 540px;
    	-webkit-border-radius: 10px;
    	-moz-border-radius: 10px;
    	border-radius: 10px;
    	text-align: left;
    	-webkit-transition: all 0.4s ease;
    	transition: all 0.4s ease;
    }
    
    .form-content h3 {
    	color: #fff;
    	text-align: left;
    	font-size: 28px;
    	font-weight: 600;
    	margin-bottom: 5px;
    }
    
    .form-content h3.form-title {
    	margin-bottom: 30px;
    }
    
    .form-content p {
    	color: #fff;
    	text-align: left;
    	font-size: 17px;
    	font-weight: 300;
    	line-height: 20px;
    	margin-bottom: 30px;
    }
    
    .form-content label,
    .was-validated .form-check-input:invalid~.form-check-label,
    .was-validated .form-check-input:valid~.form-check-label {
    	color: #fff;
    }
    
    .form-content input[type=text],
    .form-content input[type=password],
    .form-content input[type=email],
    .form-content select {
    	width: 100%;
    	padding: 9px 20px;
    	text-align: left;
    	border: 0;
    	outline: 0;
    	border-radius: 6px;
    	background-color: #fff;
    	font-size: 15px;
    	font-weight: 300;
    	color: #8D8D8D;
    	-webkit-transition: all 0.3s ease;
    	transition: all 0.3s ease;
    	margin-top: 16px;
    }
    
    .btn-primary {
    	background-color: #6C757D;
    	outline: none;
    	border: 0px;
    	box-shadow: none;
    }
    
    .btn-primary:hover,
    .btn-primary:focus,
    .btn-primary:active {
    	background-color: #495056;
    	outline: none !important;
    	border: none !important;
    	box-shadow: none;
    }
    
    .form-content textarea {
    	position: static !important;
    	width: 100%;
    	padding: 8px 20px;
    	border-radius: 6px;
    	text-align: left;
    	background-color: #fff;
    	border: 0;
    	font-size: 15px;
    	font-weight: 300;
    	color: #8D8D8D;
    	outline: none;
    	resize: none;
    	height: 120px;
    	-webkit-transition: none;
    	transition: none;
    	margin-bottom: 14px;
    }
    
    .form-content textarea:hover,
    .form-content textarea:focus {
    	border: 0;
    	background-color: #ebeff8;
    	color: #8D8D8D;
    }
    
    .mv-up {
    	margin-top: -9px !important;
    	margin-bottom: 8px !important;
    }
    
    .invalid-feedback {
    	color: #ff606e;
    }
    
    .valid-feedback {
    	color: #2acc80;
    }
    

    Finally, we will use the same JavaScript code above to prevent the user from submitting empty fields as well as to show the validation states and form validation message styles.

    I’ve compiled the code below on Codepen. Feel free to modify it and play around.

    See the Pen
    Registration Form (Bootstrap 5 Validation) by Sam Norton (@samnorton)
    on CodePen.

    Wrapping Up

    Building websites and even applications today is a lot more challenging and time-consuming than it used to be. Using Bootstrap 5 contemporary validation methods and styles will provide you an easy way, but valuable and actionable feedback to your users out of the box without worrying too much about styles.

    The best part is that you can still customize the form validation message, including the styles to your liking without reinventing the wheel.

    Like what you’re reading? Subscribe to our top stories.

    Компонент «Формы» — это набор CSS-классов, которые предназначены для оформления HTML форм: form-group, form-control, input-group, input-group-addon, input-group-btn, form-horizontal, form-inline, has-feedback, has-success, has-warning, has-error.

    Правила создания форм:

    • Поместить каждую группу элементов (например, input и связанный с ним label) в элемент div с классом form-group. Этот класс добавляет нижние отступы к группам элементов.
    • Добавить к каждому текстовому элементу управления формы input, select и textarea класс form-control. Данный класс добавляет к элементам формы стили визуального оформления, размеры и многое другое.

    В Bootstrap три вида форм: вертикальная (без добавления класса), горизонтальная (.form-horizontal) и в одну строку (.form-inline).

    Вертикальная форма

    <form>
        <div class="form-group">
            <label for="input-email">Адрес email:</label>
            <input type="email" class="form-control" id="input-email" placeholder="Введите email">
        </div>
        <div class="form-group">
            <label for="input-password">Пароль:</label>
            <input type="password" class="form-control" id="input-password" placeholder="Введите пароль">
        </div>
        <div class="form-group">
            <div class="checkbox">
                <label>
                    <input type="checkbox"> Запомнить
                </label>
            </div>
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-default">Войти</button>
        </div>
    </form>

    Горизонтальная форма

    <form class="form-horizontal">
        <div class="form-group">
            <label for="input-email" class="col-sm-2 control-label">Адрес email:</label>
            <div class="col-sm-10">
                <input type="email" class="form-control" id="input-email" placeholder="Введите email">
            </div>
        </div>
        <div class="form-group">
            <label for="inputPassword" class="col-sm-2 control-label">Пароль:</label>
            <div class="col-sm-10">
                <input type="password" class="form-control" id="inputPassword" placeholder="Введите пароль">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <div class="checkbox">
                    <label><input type="checkbox"> Запомнить</label>
                </div>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-default">Войти</button>
            </div>
        </div>
    </form>

    Форма в одну строку

    <form class="form-inline">
        <div class="form-group">
            <label for="input-email" class="sr-only">Адрес email</label>
            <input type="email" class="form-control" id="input-email" placeholder="Введите email">
        </div>
        <div class="form-group">
            <label class="sr-only" for="input-password">Пароль</label>
            <input type="password" class="form-control" id="input-password" placeholder="Введите пароль">
        </div>
        <div class="form-group">
            <div class="checkbox">
                <label>
                    <input type="checkbox"> Запомнить
                </label>
            </div>
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-default">Войти</button>
        </div>
    </form>

    Классы input-group-addon и input-group-btn

    Класс input-group-addon позволяет добавить иконки к полям формы:

    <form>
        <div class="form-group">
            <label for="input-email">Адрес email:</label>
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                <input type="email" class="form-control" id="input-email" placeholder="Введите email">
            </div>
        </div>
        <div class="form-group">
            <label for="input-password">Пароль:</label>
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
                <input type="password" class="form-control" id="input-password" placeholder="Введите пароль">
            </div>
        </div>
        <div class="form-group">
            <div class="checkbox">
                <label>
                    <input type="checkbox"> Запомнить
                </label>
            </div>
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-default">Войти</button>
        </div>
    </form>

    Класс input-group-btn позволяет объединить поле ввода и кнопку:

    <form>
        <div class="input-group">
            <input type="text" class="form-control" placeholder="Search">
            <div class="input-group-btn">
                <button class="btn btn-default" type="submit">
                    <span class="glyphicon glyphicon-search"></span>
                </button>
            </div>
        </div>
    </form>

    Подсветка полей формы

    <form>
        <div class="form-group has-success has-feedback"> <!-- класс has-success -->
            <!-- чтобы текст label был выделен цветом, нужно добавить класс control-label -->
            <label for="input-success" class="control-label">Поле ввода с иконкой success</label>
            <input type="text" class="form-control" id="input-success">
        </div>
        <div class="form-group has-warning has-feedback"> <!-- класс has-warning -->
            <!-- чтобы текст label был выделен цветом, нужно добавить класс control-label -->
            <label for="input-warning" class="control-label">Поле ввода с иконкой warning</label>
            <input type="text" class="form-control" id="input-warning">
        </div>
        <div class="form-group has-error has-feedback"> <!-- класс has-error -->
            <!-- чтобы текст label был выделен цветом, нужно добавить класс control-label -->
            <label for="input-error" class="control-label">Поле ввода с иконкой error</label>
            <input type="text" class="form-control" id="input-error">
        </div>
    </form>

    Можно еще добавить иконки:

    <form>
        <div class="form-group has-success has-feedback"> <!-- класс has-success -->
            <!-- чтобы текст label был выделен цветом, нужно добавить класс control-label -->
            <label for="input-success" class="control-label">Поле ввода с иконкой success</label>
            <input type="text" class="form-control" id="input-success">
            <span class="glyphicon glyphicon-ok form-control-feedback"></span> <!-- иконка-->
        </div>
        <div class="form-group has-warning has-feedback"> <!-- класс has-warning -->
            <!-- чтобы текст label был выделен цветом, нужно добавить класс control-label -->
            <label for="input-warning" class="control-label">Поле ввода с иконкой warning</label>
            <input type="text" class="form-control" id="input-warning">
            <span class="glyphicon glyphicon-warning-sign form-control-feedback"></span> <!-- иконка-->
        </div>
        <div class="form-group has-error has-feedback"> <!-- класс has-error -->
            <!-- чтобы текст label был выделен цветом, нужно добавить класс control-label -->
            <label for="input-error" class="control-label">Поле ввода с иконкой error</label>
            <input type="text" class="form-control" id="input-error">
            <span class="glyphicon glyphicon-remove form-control-feedback"></span> <!-- иконка-->
        </div>
    </form>

    Поиск:
    Bootstrap • CSS • HTML • Web-разработка • Верстка • Форма • Фреймворк

    Понравилась статья? Поделить с друзьями:

    Читайте также:

  • Hdd диск защищен от записи как исправить
  • Hdd smart seek error rate
  • Has been blocked by cors policy как исправить
  • Heating flow s w error
  • Has already been declared in the current scope error

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии