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 Tutorial

What is Bootstrap? Bootstrap is a CSS (Cascading Style Sheets) framework, which is used to develop a responsive website. It is an open-source and mobile-first front-end framework. It has design templates that are based...

4 minutes read.

Bootstrap Notification Bubble

What is a notification bubble? Bubbles are built into the Notification system. They float on top of the website or the button to indicate pending notifications. Bubbles can be expanded to reveal...

5 minutes read.

Bootstrap Protocol (BOOTP)

In the following article, we will learn about the Bootstrap Protocol and how it maintains contracts among linked devices on webwork. What is Bootstrap Protocol? The Bootstrap Protocol is a webwork contract...

3 minutes read.

Bootstrap 4 Popover

Bootstrap 4 Popover Popover A popover is similar to the tooltip. The only difference between tooltip and Popover is that in the tooltip, the popup box appears when you move the cursor...

6 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.

Difference between bootstrap.css and bootstrap-theme.css

The "bootstrap.css" uses to create a website with pre-existing designs and context. It uses basic Bootstrap classes like rows and columns with a CSS styling tool. The website is styled...

5 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.

Difference between Bootstrap and WordPress

What is WordPress? WordPress is a free open-source CMS (Content Management System) that is written using Hypertext Pre-processor (PHP) and is paired with MySQL and is supported with HTTPS (Hypertext Transfer...

3 minutes 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 Toast Example

What are toasts? Toasts are similar to notifications, and they are lightweight and act as push notifications from mobile and desktop operating systems. They’re built using flexbox in Bootstrap. They can...

4 minutes read.

Environment Setup

How to use Bootstrap? We can use bootstrap in our project either by downloading or by providing link of the library files. 1) Download Bootstrap files To download files, visit official site of bootstrap www.getbootstrap.com/download/ and...

1 minute read.

Bootstrap 4 Content

Typography Typography is used for styling and formatting the content. It also helps in creating customized headings, sub-headings, lists, paragraphs, etc. Headings Bootstrap 4 offers HTML heading <h1> to <h6> that has bolder...

8 minutes read.

Bootstrap 4 Inputs

Bootstrap Inputs Bootstrap Form Inputs – Several pre-defined input types are available in HTML and Bootstrap. These input types help in styling the forms. When an input type is specified in the form, it means...

10 minutes read.

Bootstrap 4 Media Objects

Bootstrap 4 Media Objects Bootstrap 4 offers a media object component that aligns the media objects and the content. The media object is used to create a repetitive and complex component...

7 minutes read.

Bootstrap 4 Jumbotron

Bootstrap 4 Jumbotron Bootstrap offers Jumbotron, which is used to get more attention to specific content or information on the web page. It provides a gray background-color to the content to make that content...

2 minutes read.

Bootstrap List group

Bootstrap list group provides a group of a list of items. The most basic list is an unordered list. We can use <ul> element with .list-group class and <li> element with .lsit-group-item. Let us see...

3 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 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 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 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.