2
0
mirror of https://github.com/tenrok/bootstrap.git synced 2026-05-15 11:59:39 +03:00
Files
bootstrap/site/content/docs/5.2/forms/validation.md
T
2022-07-23 21:57:36 +03:00

20 KiB

layout, title, description, group, toc
layout title description group toc
docs Validation Provide valuable, actionable feedback to your users with HTML5 form validation, via browser default behaviors or custom styles and JavaScript. forms true

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 data-bs-toggle="form" <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.

{{< example >}}

@
Choose... ...
Submit form Reset form
{{< /example >}}

{{< example lang="js" show_preview="false" >}} {{< js.inline >}} {{< /js.inline >}} {{< /example >}}

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.

{{< example >}}

@
Choose... ...
Submit form
{{< /example >}}

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.

Ensure that the 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 radius, input groups require an additional .has-validation class.

{{< example >}}

Looks good!
Looks good!
@
Please choose a username.
Please provide a valid city.
Choose... ...
Please select a valid state.
Please provide a valid zip.
You must agree before submitting.
Submit form
{{< /example >}}

Supported elements

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

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

{{< example >}}

Please enter a message in the textarea.
Example invalid feedback text
More example invalid feedback text
Open this select menu One Two Three
Example invalid select feedback
Example invalid form file feedback
Submit form
{{< /example >}}

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 on it for tooltip positioning. In the example below, our column classes have this already, but your project may require an alternative setup.

{{< example >}}

@
Choose... ...
Submit form Reset form
{{< /example >}}

Sass

Variables

{{< scss-docs name="form-feedback-variables" file="scss/_variables.scss" >}}

Mixins

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

{{< scss-docs name="form-validation-mixins" file="scss/mixins/_forms.scss" >}}

Map

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

{{< scss-docs name="form-validation-states" file="scss/_variables.scss" >}}

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.

{{< scss-docs name="form-validation-states-loop" file="scss/forms/_validation.scss" >}}

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.

Usage

Via data attributes

To easily add form validation behavior to you form, add data-bs-toggle="form" attribute to the <form> element.

Via JavaScript

Enable manually with:

const formElementList = document.querySelectorAll('form')
const formList = [...formElementList].map(formEl => new bootstrap.Form(formEl))

Options

Form

{{< bs-table "table" >}}

Name Type Default Description
type string feedback You may pick the kind of feedback. Acceptable values tooltip or feedback
validateCallback function, null null A callback to execute while trying to check for errors. Can be use for ajax submissions/validations.
{{< /bs-table >}}

Field

{{< bs-table "table" >}}

Name Type Default Description
invalid string '' invalid message to append
valid string '' valid message to append
{{< /bs-table >}}

Methods

You can create a form instance using the constructor, for example:

const bsForm = new bootstrap.Form('#myForm', { type: 'tooltip' })

Form

{{< bs-table "table" >}}

Method Description
getInstance Static method which allows you to get the form instance associated with a DOM element.
getOrCreateInstance Static method which allows you to get the form instance associated with a DOM element, or create a new one in case it wasn't initialized.
getElement Returns the DOM element of the instance.
getFields Returns all form-fields instances of the form. Array<FormField>.
getField('name') Searches and return the requested FormField instance or undefined.
clear Clears all the form validation results.
validate Activates validation process.
{{< /bs-table >}}

Field

{{< bs-table "table" >}}

Method Description
getInstance Static method which allows you to get the form Field instance associated with a DOM element
getOrCreateInstance Static method which allows you to get the form Field instance associated with a DOM element, or create a new one in case it wasn't initialized
getElement Returns the DOM element of the instance.
clearAppended Clears any appended messages from field.
appendError(message) Appends the given message as an error feedback. In case we do not provide a message, it fallbacks to the configuration given invalid message.
appendSuccess(message) Appends the given message as a success feedback. In case we do not provide a message, it fallbacks to the configuration given valid message.
appendFeedback(message) Appends the given message as a simple info feedback.
name returns the name (fallback to id) of the field as unique identifier between form elements.
{{< /bs-table >}}