Hit enter after type your search item

Bootstrap 5 Form Validation [5 Demos with Code]

Doing Form Validation in Bootstrap 5

Bootstrap 5 provides custom styles by using HTML 5 form validation. Besides, you may also provide feedback/tips to the users via browser default behaviors as well as JavaScript.

The form validation can be applied to input fields like textboxescheckboxes, radio buttons, or select elements and textarea.

You may show descriptive messages and tooltips as well while validating forms as guiding users submitting the forms.

An example of BS 5 form validation with browser default style

Before creating a form validation with custom CSS and JavaScript, let us have a look at a form with browser’s default style.

So, the style depends on which browser you are using on which OS. A Windows OS form may look different than the form in Mac, Linux etc.

Have a look at the form below and we will describe how it is done:

See online demo and code

BS5-validation


In order to make a form field mandatory, you need to add the required attribute.

An example of browser default form with more form fields

In this example, we have a select control and a checkbox to be validated. These are given the required attribute as well:

See online demo and code

BS5-validation-more

An example of custom CSS and JavaScript based form validation using BS 5

In order to use the custom styles in Bootstrap 5, you need to do two things:

  • In the <form>, you need to add the novalidate This is a Boolean attribute that will supress default feedback tooltips of the browser.
  • Use the :invalid and :valid styles (provided by BS 5 and applies automatically or you may customize this as well)

See an example below with various form controls and submit the form. You will see a custom style form validation in action:

See online demo and code

BS5-validation-custom


Notice the JavaScript before the </body> tag.

An example of validating textarea, checkbox, and radio buttons

As mentioned earlier, you may also validate checkbox and radio buttons. You have seen checkbox in above example. For example, you need to confirm user if he/she agrees with the term & conditions via the checkbox’s checked/unchecked option.

Similarly, asking the user for the male/female option via radio buttons and so on.

See an example of validating the checkbox and radio button and textarea below:

See online demo and code

validation-radio-check

Using tooltips for form validation example

If you want to display validation messages as styled tooltips, you need to swap:

.{valid|invalid}-feedback classes  To

.{valid|invalid}-tooltip classes

See online demo and code

validation-tooltips


For reference and more details: https://getbootstrap.com/docs/5.0/forms/validation/
This div height required for enabling the sticky sidebar