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-check
s
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.
(UPDATED with examples for Bootstrap v4, v3 and v3)
Examples of forms with validation classes for the past few major versions of Bootstrap.
Bootstrap v4
See the live version on codepen
<div class="container">
<form>
<div class="form-group row">
<label for="inputEmail" class="col-sm-2 col-form-label text-success">Email</label>
<div class="col-sm-7">
<input type="email" class="form-control is-valid" id="inputEmail" placeholder="Email">
</div>
</div>
<div class="form-group row">
<label for="inputPassword" class="col-sm-2 col-form-label text-danger">Password</label>
<div class="col-sm-7">
<input type="password" class="form-control is-invalid" id="inputPassword" placeholder="Password">
</div>
<div class="col-sm-3">
<small id="passwordHelp" class="text-danger">
Must be 8-20 characters long.
</small>
</div>
</div>
</form>
</div>
Bootstrap v3
See the live version on codepen
<form role="form">
<div class="form-group has-warning">
<label class="control-label" for="inputWarning">Input with warning</label>
<input type="text" class="form-control" id="inputWarning">
<span class="help-block">Something may have gone wrong</span>
</div>
<div class="form-group has-error">
<label class="control-label" for="inputError">Input with error</label>
<input type="text" class="form-control" id="inputError">
<span class="help-block">Please correct the error</span>
</div>
<div class="form-group has-info">
<label class="control-label" for="inputError">Input with info</label>
<input type="text" class="form-control" id="inputError">
<span class="help-block">Username is taken</span>
</div>
<div class="form-group has-success">
<label class="control-label" for="inputSuccess">Input with success</label>
<input type="text" class="form-control" id="inputSuccess" />
<span class="help-block">Woohoo!</span>
</div>
</form>
Bootstrap v2
See the live version on jsfiddle
The .error
, .success
, .warning
and .info
classes are appended to the .control-group
. This is standard Bootstrap markup and styling in v2. Just follow that and you’re in good shape. Of course you can go beyond with your own styles to add a popup or «inline flash» if you prefer, but if you follow Bootstrap convention and hang those validation classes on the .control-group
it will stay consistent and easy to manage (at least since you’ll continue to have the benefit of Bootstrap docs and examples)
<form class="form-horizontal">
<div class="control-group warning">
<label class="control-label" for="inputWarning">Input with warning</label>
<div class="controls">
<input type="text" id="inputWarning">
<span class="help-inline">Something may have gone wrong</span>
</div>
</div>
<div class="control-group error">
<label class="control-label" for="inputError">Input with error</label>
<div class="controls">
<input type="text" id="inputError">
<span class="help-inline">Please correct the error</span>
</div>
</div>
<div class="control-group info">
<label class="control-label" for="inputInfo">Input with info</label>
<div class="controls">
<input type="text" id="inputInfo">
<span class="help-inline">Username is taken</span>
</div>
</div>
<div class="control-group success">
<label class="control-label" for="inputSuccess">Input with success</label>
<div class="controls">
<input type="text" id="inputSuccess">
<span class="help-inline">Woohoo!</span>
</div>
</div>
</form>
Нам известно, что в настоящее время пользовательские стили проверки и всплывающие подсказки на стороне клиента недоступны, поскольку они недоступны для вспомогательных технологий. Пока мы работаем над решением, мы рекомендуем использовать либо серверную опцию, либо метод проверки браузера по умолчанию.
Как это работает
Вот как валидация форм работает с 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
.
В настоящее время мы рекомендуем использовать настраиваемые стили проверки, поскольку сообщения проверки по умолчанию в собственном браузере не всегда доступны вспомогательным технологиям во всех браузерах (в первую очередь, в Chrome для настольных и мобильных устройств).
Как это устроено
Вот как проверка формы работает с Bootstrap:
- Проверка формы HTML применяется через два псевдокласса CSS
:invalid
и:valid
. Это относится и к<input>
,<select>
и<textarea>
элементы. - Bootstrap привязывает
:invalid
и:valid
стили родительского.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>
. Это отключает всплывающие подсказки обратной связи браузера по умолчанию, но по-прежнему обеспечивает доступ к API проверки формы в JavaScript. Попробуйте заполнить форму ниже; наш JavaScript перехватит кнопку отправки и передаст вам отзыв. При попытке подать, вы увидите :invalid
и :valid
стили применяются к элементам управления формы.
В пользовательских стилях обратной связи применяются пользовательские цвета, границы, стили фокуса и фоновые значки, чтобы лучше передавать отзывы. Фоновые значки для <select>
доступны только с .form-select
, но не .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">
<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)
})
})()
Настройки браузера по умолчанию
Не заинтересованы в настраиваемых сообщениях обратной связи для проверки или написании JavaScript для изменения поведения формы? Все хорошо, вы можете использовать настройки браузера по умолчанию. Попробуйте заполнить форму ниже. В зависимости от вашего браузера и ОС вы увидите немного другой стиль обратной связи.
Хотя эти стили обратной связи нельзя стилизовать с помощью CSS, вы все равно можете настроить текст отзыва с помощью 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>
Сторона сервера
Мы рекомендуем использовать проверку на стороне клиента, но если вам требуется проверка на стороне сервера, вы можете указать недопустимые и допустимые поля формы с помощью .is-invalid
и .is-valid
. Обратите внимание, что .invalid-feedback
это также поддерживается этими классами.
<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">
<span class="input-group-text" id="inputGroupPrepend3">@</span>
<input type="text" class="form-control is-invalid" id="validationServerUsername" aria-describedby="inputGroupPrepend3" required>
<div 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" required>
<div 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" 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="validationServer05" class="form-label">Zip</label>
<input type="text" class="form-control is-invalid" id="validationServer05" 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 is-invalid" type="checkbox" value="" id="invalidCheck3" required>
<label class="form-check-label" for="invalidCheck3">
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>
Поддерживаемые элементы
Стили проверки доступны для следующих элементов управления и компонентов формы:
<input>
и<textarea>
с.form-control
(включая до одного.form-control
во входных группах)<select>
с.form-select
.form-check
.form-file
Textarea
Пожалуйста, введите сообщение в текстовое поле.
Установите этот флажок
Пример неверного текста отзыва
Переключить это радио
Или переключите это другое радио
Еще пример недопустимого текста отзыва
Пример неверного отзыва о выборе
Выбрать файл…
Просматривать
Пример неверной обратной связи с файлом формы
<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="form-file mb-3">
<input type="file" class="form-file-input" id="validationFormFile" required>
<label class="form-file-label" for="validationFormFile">
<span class="form-file-text">Choose file...</span>
<span class="form-file-button">Browse</span>
</label>
<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>
Если макет формы позволяет это, вы можете поменять .{ 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">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">
<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 с $form-validation-states
картой. _variables.scss
эта карта Sass, расположенная в нашем файле, зацикливается для генерации состояний по умолчанию valid
/ invalid
проверки. Включена вложенная карта для настройки цвета и значка каждого состояния. Хотя браузеры не поддерживают никакие другие состояния, те, кто использует настраиваемые стили, могут легко добавить более сложную обратную связь с формой.
Обратите внимание, что мы не рекомендуем настраивать эти значения без изменения form-validation-state
миксина.
Это карта Sass из _variables.scss
. Переопределите это и перекомпилируйте свой Sass для генерации разных состояний:
$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
)
);
Это петля из forms/_validation.scss.scss
. Любые изменения в приведенной выше карте Sass будут отражены в вашем скомпилированном CSS через этот цикл:
@each $state, $data in $form-validation-states {
@include form-validation-state($state, map-get($data, color), map-get($data, icon));
}
Bootstrap Validation
Note: This documentation is for an older version of Bootstrap (v.4). A
newer version is available for Bootstrap 5. We recommend migrating to the latest version of our product — Material Design for
Bootstrap 5.
Go to docs v.5
Provide valuable, actionable feedback to your users with HTML5 form validation – available in all our supported browsers. Choose from the browser default validation feedback,
or implement custom messages with our built-in classes and starter JavaScript.
Note: For advanced users we recommend using custom validation described in this tutorial because styles as native browser defaults are not announced to screen readers.
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 their parent.was-validated
class, usually applied to the<form>
. Otherwise, any required field without a value shows up
as invalid when a page is loaded. This way, you may choose when to activate them (typically after the 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 use 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, examine 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.
Default styles
Browser defaults
Not interested in custom validation feedback messages or writing JavaScript to change
form behaviors? That’s fine, 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.
Default styles
Server side
We recommend using client-side validation, but in case you require server side, you can
indicate invalid and valid form fields with .is-invalid
and .is-valid
. Note that .invalid-feedback
is also supported by these classes.
Default styles
Material styles
Supported elements
Our example forms show native textual <input>
s above, but form
validation styles are available for our custom form controls, as well.
Default styles
Tooltips
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
to it for tooltip positioning. In the example below,
our
column classes have this already, but your project may require an alternative setup.
Default styles
DatePicker Validation MDB Pro component»
Material Select Validation MDB Pro component»
Agree to terms and conditions
You shall not pass!
Bootstrap • March 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:
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:
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:
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:
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.
На этом уроке мы рассмотрим, как можно с помощью классов Twitter Bootstrap 3 изменять состояние элементов управления формы при её проверке с помощью встроенных средств HTML5.
Использование классов Twitter Bootstrap 3 для отображения результатов проверки формы
Перед отправкой формы на сервер, её заполнение обычно проверяют с помощью скриптов JavaScript или встроенного в HTML 5 метода checkValidity()
. Эта процедура исключает обработку сервером неверно заполненных данных пользователем, а также разгружает сервер посредством уменьшения количества запросов к нему.
На этом уроке, для проверки правильности заполнения полей формы, мы будем использовать встроенный в HTML 5 метод checkValidity()
. А подсказывать пользователю, правильно ли он заполнил поле или нет в форме, будем с помощью классов Twitter Bootstrap 3 .has-warning
, .has-error
и has.success
.
В качестве примера рассмотрим форму для регистрации, которую будем открывать в модальном окне с помощью соответствующей кнопки на веб-странице.
Процесс создания формы и её валидации представим в виде следующих шагов:
-
Создадим форму для регистрации пользователя.
Для отображения иконки (в области
c
), показывающей результат валидации данных, необходимо добавить класс.has-feedback
к контейнеру<div class="form-group">
…</div>
и элемент<span class="glyphicon form-control-feedback">
</span>
для каждого блока формы.<!-- Форма для регистрации --> <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 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>
-
Создадим кнопку для вызова модального окна.
<!-- Кнопка для открытия модального окна --> <button type="button" class="btn btn-lg btn-success" data-toggle="modal" data-target="#myModal"> Регистрация </button>
-
Создадим сообщение, которое будет отображаться при закрытии модального окна. Сообщение будет отображаться только в том случае, если пользователь нажал на кнопку «Регистрация» и форма в этот момент валидна.
<div class="alert alert-success hidden" id="success-alert"> <h2>Успех</h2> <div>Ваши данные были успешно отправлены.</div> </div>
-
Напишем скрипт, который будет проверять данные в элементах управления формы на правильность заполнения с помощью метода 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
.
<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>
- добавляем класс
-
В итоге у нас получился следующий код:
<!--...--> <!-- Подлючаем 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> <!--...-->
Демо
In the web development world, we deal with form validation almost at every step. Whether it is a sign-in or login form, sign-up or registration form, contact us form, any form may emerge from anywhere.
In this tutorial, we will learn how to implement validation in the Bootstrap 4 form with Bootstrap Validator third party plugin.
The best thing about validator.js library is, you don’t have to wait until the web page gets refreshed to display the validation errors. It manifests form validation errors when the user starts typing in the form’s input field.
Our Bootstrap 4 Form validation with Validator.JS demo is solely dependent on Validate.js, So let us know a little bit about it.
Validate.js offers simple yet powerful ways to validate Bootstrap form input or elements. You can get this project from GitHub, and yes, you can share your valuable feedback.
This plugin makes client-side validation in Bootstrap super easy, and even you don’t require to refresh the page to get the form errors. It is not limited to just Bootstrap. Instead, you can use other language frameworks such as Codeigniter, Symphony, Laravel, and many more.
Let us invoke the most important task of this Bootstrap 4 Form Validation tutorial. We have to add the Bootstrap 4 and Bootstrap Validator CSS (Validator.js) via the CDN link. Open your HTML template and place the following CSS and jQuery links in the head section.
<head>
<title> Bootstrap 4 Form Validation with Validator.js Example | positronx.io</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"></link>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js"></script>
</head>
Create Form with Bootstrap
Bootstrap form design is a quintessential craft of team bootstrap. Bootstrap UI elements helpful in sustaining the impetus of web development, we have already added the Bootstrap UI framework CSS.
Now, we are creating the Form using one such element of Bootstrap UI. It makes the form validation process in Bootstrap easy.
<form role="form">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" id="inputName" placeholder="Name">
</div>
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" id="inputUsername" placeholder="Username">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" id="inputEmail" placeholder="Email">
</div>
<div class="form-group">
<label>Password</label>
<div class="form-group">
<input type="password" class="form-control" id="inputPassword" placeholder="Password">
</div>
</div>
<div class="form-group">
<label>Confirm Password</label>
<div class="form-group">
<input type="password" class="form-control" id="inputConfirmPassword" placeholder="Confirm">
</div>
</div>
<div class="form-group">
<label>Message</label>
<textarea class="form-control" id="inputMessage" placeholder="Message" required=""></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Send</button>
</div>
</form>
Final Bootstrap 4 Form Validation Example
Eventually, everything has been placed at its place. Now, i will show you how to add validation in Bootstrap form and display custom error messages.
We will implement the following validations in our form.
- Required
- Min Length
- Max Length
- Password Confirmation
<html class="no-js" lang="en">
<head>
<title> Bootstrap 4 Form Validation with Validator.js Example | positronx.io</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"></link>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js"></script>
<style>
body {
background: #EECDA3;
background: -webkit-linear-gradient(to top, #EF629F, #EECDA3);
background: linear-gradient(to top, #EF629F, #EECDA3);
}
.container {
max-width: 550px;
}
.has-error label,
.has-error input,
.has-error textarea {
color: red;
border-color: red;
}
.list-unstyled li {
font-size: 13px;
padding: 4px 0 0;
color: red;
}
</style>
</head>
<body>
<div class="container mt-5">
<div class="card">
<h5 class="card-header text-center">Bootstrap 4 Form Validation Demo</h5>
<div class="card-body">
<form role="form" data-toggle="validator">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" data-error="You must have a name." id="inputName" placeholder="Name" required>
<!-- Error -->
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" name="username" maxlength="10" minlength="3"
pattern="^[a-zA-Z0-9_.-]*$" id="inputUsername" placeholder="Username" required>
<!-- Error -->
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" id="inputEmail" placeholder="Email" required>
<!-- Error -->
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label>Password</label>
<div class="form-group">
<input type="password" data-minlength="4" class="form-control" id="inputPassword"
data-error="Have atleast 4 characters" placeholder="Password" required />
<!-- Error -->
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label>Confirm Password</label>
<div class="form-group">
<input type="password" class="form-control" id="inputConfirmPassword"
data-match="#inputPassword" data-match-error="Password don't match"
placeholder="Confirm" required />
<!-- Error -->
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label>Message</label>
<textarea class="form-control" data-error="Please enter message." id="inputMessage"
placeholder="Message" required=""></textarea>
<!-- Error -->
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Send</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Finally, we have completed this tutorial. In the above form validation example, we have highlighted the necessary validations.
The Bootstrap validator plugin is a user-friendly and straightforward form validator plugin, and it works smoothly.
Form Validation
Username:
Valid.
Please fill out this field.
Password:
Valid.
Please fill out this field.
I agree on blabla.
Valid.
Check this checkbox to continue.
You can use different validation classes to provide valuable feedback to
users. Add either .was-validated
or .needs-validation
to the <form>
element,
depending on whether you want to provide validation feedback before or after
submitting the form. The input fields will have a green (valid) or red (invalid)
border to indicate what’s missing in the form. You can also add a
.valid-feedback
or .invalid-feedback
message to tell the user explicitly what’s
missing, or needs to be done before submitting the form.
Example
In this example, we use .was-validated
to indicate what’s missing before submitting the form:
<form action=»/action_page.php» class=»was-validated»>
<div
class=»mb-3 mt-3″>
<label for=»uname»
class=»form-label»>Username:</label>
<input type=»text»
class=»form-control» id=»uname» placeholder=»Enter username» name=»uname»
required>
<div class=»valid-feedback»>Valid.</div>
<div class=»invalid-feedback»>Please fill out this field.</div>
</div>
<div class=»mb-3″>
<label for=»pwd»
class=»form-label»>Password:</label>
<input
type=»password» class=»form-control» id=»pwd» placeholder=»Enter password»
name=»pswd» required>
<div
class=»valid-feedback»>Valid.</div>
<div
class=»invalid-feedback»>Please fill out this field.</div>
</div>
<div class=»form-check mb-3″>
<input
class=»form-check-input» type=»checkbox» id=»myCheck» name=»remember»
required>
<label class=»form-check-label»
for=»myCheck»>I agree on blabla.</label>
<div
class=»valid-feedback»>Valid.</div>
<div
class=»invalid-feedback»>Check this checkbox to continue.</div>
</div>
<button type=»submit» class=»btn btn-primary»>Submit</button>
</form>
Try it Yourself »
The form validation in Bootstrap
In HTML 5, the default form validation is done for the fields marked with the required attribute. It will even check the email format for the field specified as type=”email” with the required attribute.
However, the message is basic and displayed as:
“Please fill in the field”
Where the specific field will also get focus as you try to submit the form.
Simple validation demo
Custom error message demo
As using the Bootstrap framework for creating the forms, the same default validation is applied. If you want to customize the validation messages for the form fields like displaying the field related message:
“You must enter your name” etc.
You may use JavaScript / jQuery for that. See the following section for simple and custom form validation using Bootstrap framework with jQuery.
Do you know? In Bootstrap 4, there is built-in support for the form validation with custom messages without using the jQuery. You simply require adding the Bootstrap 4 CSS and write a little JavaScript code. You can see an example here. For full tutorial about forms in Bootstrap 4 including validation go to this tutorial: Bootstrap 4 forms
A demo of simple form validation
In this demo, the Bootstrap form validation is done by using the default behavior. Only the required attribute is added for the fields. Go to the demo page and press the submit button and see how validation message appears:
See online demo and code
The markup for this demo:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<div class=«container»> <h1>Form validation demo</h1> </div> <form class=«form»> <div class=«container»> <div class=«row»> <div class=‘col-sm-4 form-group’> <label for=«name»>First Name:</label> <input id=«fname» class=«form-control» type=«text» required> </div> <div class=‘col-sm-4 form-group’> <label for=«name»>Last Name:</label> <input id=«lname» class=«form-control» min=«3» required> </div> <div class=‘col-sm-4 form-group’> <label for=«name»>Email address:</label> <input id=«email» class=«form-control» type=«email» required> </div> </div> <div class=«row»> <div class=«col-sm-4 col-sm-offset-4»> <button type=«submit» class=«btn btn-success btn-block»>Submit</button> </div> </div> </div> |
You can see, only adding the required attribute will not let move ahead if the field is left blank. In the case of email address, the format of the email is also checked as shown in the second graphic.
Also, you saw the standard messages are shown i.e. “Please fill in this field” with an icon.
A demo of Bootstrap form validation with jQuery for custom error message
In this demo, a jQuery plug-in is used for validating Bootstrap form. A number of different types of fields are used in the form. For displaying a custom error message rather a single standard message you may use the data-error-msg attribute with each input type. For example, for the name field, you may specify the following message by using the data-error-msg data attribute:
“Please enter the name!”
Similarly, you may specify the message according to the field.
See online demo and code
The code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 |
<div class=«container»> <h1>A demo of Bootstrap validate form</h1> </div> <!— don’t forget novalidate to stop browser form validation —> <form class=«form»> <div class=«container»> <div class=«row»> <div class=‘col-sm-4 form-group’> <label for=«name»>Your Name:</label> <input id=«lname» class=«form-control» min=«3» required type=«text» data-error-msg=«Must enter your name?»> </div> <div class=‘col-sm-4 form-group’> <label for=«name»>Email:</label> <input id=«email» class=«form-control» type=«email» required data-error-msg=«The email is required in valid format!»> </div> </div> <div class=‘row’> <div class=‘col-sm-4 form-group’> <label for=‘address’>Address: (optional)</label> <input id=‘address’ class=‘form-control’ type=‘text’> </div> </div> <div class=«row»> <div class=‘col-sm-4 form-group’> <label for=‘terms’>Agree with T&Cs?</label> <select id=‘terms’ class=‘form-control’ required> <option selected disabled>Select </option> <option value=«Y»>Yes</option> <option value=«N»>No</option> </select> </div> <div class=‘col-sm-4 form-group’> <div class=«checkbox»> <label> <input type=«checkbox» name=«option1» value=«» required data-error-msg=«You have to select one expertise.»> HTML </label> </div> <div class=«checkbox disabled»> <label> <input type=«checkbox» name=«option1» value=«»> CSS </label> </div> </div> <div class=‘col-sm-4 form-group’> <div class=«radio»> <label> <input type=«radio» name=«optionsRadios» id=«optionsRadios1» value=«option1»> Python </label> </div> <div class=«radio»> <label> <input type=«radio» name=«optionsRadios» id=«optionsRadios2» value=«option2»> Java </label> </div> <div class=«radio disabled»> <label> <input type=«radio» name=«optionsRadios» id=«optionsRadios3» value=«option3»> SQL </label> </div> </div> </div> <div class=«row»> <div class=«col-sm-4 col-sm-offset-4»> <button type=«submit» class=«btn btn-danger btn-block»>Proceed</button> </div> </div> </div> |
The jQuery code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<script> $(function() { $(‘form’).validator({ validHandlers: { ‘.customhandler’:function(input) { //may do some formatting before validating input.val(input.val().toUpperCase()); //return true if valid return input.val() === ‘JQUERY’ ? true : false; } } }); $(‘form’).submit(function(e) { e.preventDefault(); if ($(‘form’).validator(‘check’) < 1) { alert(‘Hurray, your information will be saved!’); } }) }) </script> |
You can see, I have used the textboxes for the name and email while radio buttons and checkboxes are also used. The radios are optional while you have to check at least one checkbox. If all is well, the alert will display the following message:
“Hurray, your information will be saved!”
Otherwise, the error message will keep on displaying.
The validate plug-in
You may download this nice plug-in from the GitHub website here. After downloading, just include the validate-bootstrap.jquery.min.js file after referencing the jQuery and Bootstrap JS files.
This div height required for enabling the sticky sidebar