Bootstrap Validation Example

Validation

We can provide valuable and actionable feedback to the users through an HTML form validation. It happens via custom styles or behaviors of default browsers and JavaScript.

How does validation work in Bootstrap?

  • The two pseudo-classes in CSS (Cascading Style Sheets) are used for HTML form validation, they are:
    •  :invalid 
    •  :valid

 It is applied to the <input>, <select>, and <textarea> elements.

  • Bootstrap is used to set the scope of these two pseudo-classes:  the :invalid and :valid styles into the parent class: .was-validated.
  • These are applied within the <form> element usually. However, if not, any required field without a value would appear invalid when the page is loaded.
  • Through this method, we can choose whether we want to activate them and when to activate them (typically after form submission is attempted).
  • If we want to reset the appearance of the form, then remove the  .was-validated parent class from the <form> element again after the submission.

NOTE: If .is-invalid and .is-valid classes are used instead of the pseudo-classes for server-side validation, then no parent class is required, i.e.,  .was-validated parent class is not needed.

  • Custom styles cannot be applied to the <label> element that comes before a form control in the DOM. Custom JavaScript can be used to apply styles.
  • Form validation is supported by mostly all browsers like
  • Custom feedback styles along with HTML and CSS or browser defaults are utilized for feedback messages.
  • Custom validity messages can be added. The class setCustomValidity in JavaScript, is used for it.

Custom form validation styles

In custom styles, we can change the custom font colours, font styles, buttons, and background colours to better communicate feedback.

NOTE: If we want to add background icons, they are available only with .form-select, and not .form-control(for <select> element).

The novalidate boolean attribute is used along with the <form> element for custom Bootstrap form validation messages. This disables the browser default feedback tooltips. However, it still provides access to the form validation APIs in JavaScript.

Following is an example that shows the :invalid and :valid styles applied to the form controls.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
    <title>Validation</title>
</head>
<body style="background-color: #dfe4ea; ">
<div class="container">
<div class="row">   
<p>Following is an example demonstrating form validation using custom styles:</p> 
<form class="row g-3 needs-validation" novalidate>
  <div class="col-md-4">
    <label for="validationCustom01" class="form-label">Enter your first name : </label>
    <input type="text" class="form-control" id="validationCustom01" value="Rahul" required>
    <div class="valid-feedback">
      The field is accepted!
    </div>
  </div>
  <div class="col-md-4">
    <label for="validationCustom02" class="form-label">Enter your last name : </label>
    <input type="text" class="form-control" id="validationCustom02" value="Sharma" required>
    <div class="valid-feedback">
        The field is accepted!
    </div>
  </div>
  <div class="col-md-4">
    <label for="validationCustom06" class="form-label">Enter your age : </label>
    <input type="text" class="form-control" id="validationCustom06" value="21" required>
    <div class="valid-feedback">
        The field is accepted!
    </div>
  </div>
  <br>
  <div class="col-md-4">
    <label for="validationCustomUsername" class="form-label">Enter a valid 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>
  <br><br>
  <div class="col-md-6">
    <label for="validationCustom03" class="form-label">Choose your city : </label>
    <select class="form-select" id="validationCustom03" required>
        <option selected disabled value="">Select...</option>
        <option>Agra</option>
        <option>Lucknow</option>
        <option>Aligarh</option>
        <option>Kanpur</option>
        <option>Meerut</option>
      </select>
     <div class="invalid-feedback">
      Please select a valid city.
    </div>
  </div>
  <div class="col-md-3">
    <label for="validationCustom04" class="form-label">Choose your state : </label>
    <select class="form-select" id="validationCustom04" required>
      <option selected disabled value="">Select...</option>
      <option>Uttar Pradesh</option>
    </select>
    <div class="invalid-feedback">
      Please select a valid state.
    </div>
  </div>
  
  <div class="col-md-3">
    <label for="validationCustom06" class="form-label">Choose your country : </label>
    <select class="form-select" id="validationCustom05" required>
      <option selected disabled value="">Select...</option>
      <option>India</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 enter a valid zip code.
    </div>
  </div>
  <div class="col-12">
    <div class="form-check">
      <input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
      <label class="form-check-label" for="invalidCheck">
        I agree to terms and conditions.
      </label>
      <div class="invalid-feedback">
        You must agree to the terms and conditions before submitting.
      </div>
    </div>
  </div>
  <div class="col-12">
    <button class="btn btn-secondary" type="submit">Submit</button>
  </div>
</form>
</div>
</div>
<script>
(function () {
  'use strict'


  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)
    })
})()
</script>
</body>
</html>

Output:

Bootstrap Validation Example

The following messages will be displayed if the user tries to submit the form without filling all the fields,

Bootstrap Validation Example

Related Topics

Bootstrap 4 Grid Classes

Bootstrap 4 Grid Classes Extra-small Grid – In the extra-small grid system class, when you create the grid (columns), the columns will not be stacked on top of each other on...

8 minutes read.

Bootstrap 4 Filters

 Bootstrap 4 Filters Bootstrap 4 provides a filter component that is used to search an element from a list, table, etc. Bootstrap does not contain any component or utility that helps...

5 minutes read.

Bootstrap 4 Flex

Bootstrap 4 Flex Flex is a Bootstrap 4 component used to manage the layout, navigation bar, grid columns, sizing, alignment, and other components. The flexbox or flex utility is the replacement...

26 minutes read.

Bootstrap 4 navbar

A navigation navbar or navbar uses in every website to make it more user-friendly. Navigating through the website is easier, and the user can instantly search for the topic of...

8 minutes read.

Bootstrap 4 Carousel

Bootstrap 4 Carousel Bootstrap 4 offers a carousel component, which is also known as a slider or slideshow. The carousel is used for the dynamic representation of content using images with...

7 minutes read.

Bootstrap Tabs and Pills

Bootstrap Menus Bootstrap menu is used to create different types of menu. It can created horizontal with its .list-inlineclass. <div class="container">       <h3>Example of Bootstrap Menu</h3>       <ul class="list-inline">         <li><a href="#">Home</a></li>         <li><a href="#">About</a></li>         <li><a href="#">Contact</a></li>         <li><a href="#">services</a></li>       </ul>     </div> Try Now Bootstrap Tabs Bootstrap tabl is look like is menu but there is some difference....

4 minutes read.

Bootstrap 4 Tooltip

Bootstrap 4 Tooltip Tooltip Bootstrap 4 offers a tooltip component, a small popup box that appears when you move the cursor over an element such as buttons or any highlighted element. It...

3 minutes read.

Bootstrap 4 Grid System

Bootstrap 4 Grid Systems Bootstrap offers a responsive and mobile-first grid system with the help of which we can divide the screen of the web browser into 12 horizontal parts. It has predefined classes...

4 minutes read.

Bootstrap 4 Progress Bar

Bootstrap Progress Bar Bootstrap 4 offers progress bars that are used to represent the progress of tasks such as downloading a file, software installation, etc. on the computer. It represents the percentage of the...

9 minutes read.

Bootstrap Panels

A bootstrap panel is used to create bordered box with some padding around its content. It is created with the .panels classes, and .panel-body classes. There are following classes of the panel: Panel header Panel...

4 minutes read.

Bootstrap 4 Colors

Bootstrap 4 Colors Bootstrap 4 consists of classes that are used to set colors according to the context of the element, and with the help of these classes, we can read...

2 minutes read.

Bootstrap Datepicker

What is a Bootstrap Datepicker? It is used to display a calendar with the date, month, and time from a dropdown menu. We will use an example to see how the date...

5 minutes read.

Bootstrap 4 Pagination

Bootstrap 4 Pagination Bootstrap pagination is used to show the existence of a series of web pages of the website. It allows navigation on multiple pages of a website. In pagination, there is a block...

9 minutes read.

Bootstrap Wells

In Bootstrap, well are used to add a rounded border around an element. It is default some padding and gray background color. It is like a container that displays the content....

1 minute read.

Bootstrap Badges and Labels

Bootstrap Badges Bootstrap Badges are numerical indicators. It is used to show that how many items are associated with a link.The .badge class is used to create of Bootstrap Badges. Let us see...

2 minutes read.

Bootstrap Navigation bar

Navigation Bars In Bootstrap, We can create navigation bar like a navigation header. It is placed at the top of the page. We can collapse or extend it according to screen...

3 minutes read.

Bootstrap Multiselect Dropdown

What is a multi-select Dropdown? Multi-select dropdown lists are used when we want to select multiple options for a particular record. Usually, dropdown lists provide the feature of choosing just one value...

4 minutes read.

Bootstrap 4 Toast

Bootstrap 4 Toast Bootstrap 4 offers a Toast component, which is quite similar to the alert box and pushes notifications. The toast is visible on the screen for a few seconds when any...

5 minutes read.

Bootstrap 4 Dropdowns

Bootstrap Dropdowns Bootstrap 4 provides a dropdown component, which is a toggle and contextual layout, used to display a predefined list of links. It allows the user to select a value from the dropdown...

15 minutes read.

Bootstrap 4 Scrollspy

Bootstrap 4 Scrollspy Bootstrap 4 offers a scrollspy component that is used to make the website more attractive and eye-catching. Basically, the scrollspy is used on the single-page website. The scrollspy highlights the nav...

5 minutes read.