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

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

CakePHP Layouts & Elements

A layout includes a presentation code that can be wrapped out in your view. It means that what you want to see in your view should be well-positioned in layout. When you create...

9 minutes read.

Bootstrap Contact Us page

What is a “Contact Us” page? A “Contact Us” page is a web page available on the websites of various companies, organisations etc., for its users to contact the organisation or...

5 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 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 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 First Example

1) Add HTML5 doctype Before starting the example of Bootstrap, we should know about the some basic rules of Bootstrap. We have to add HTML5 doctype with lang element and CSS properties. <!DOCTYPE html>   <html lang="en">     <head>       <meta charset="utf-8">      </head>   </html> 2) Bootstrap...

2 minutes read.

Bootstrap Pager

← Prev Next → ...

1 minute read.

Bootstrap 4 Grid System

Bootstrap 4 Grid System The bootstrap 4 grid system is used to create a responsive website layout. The bootstrap 4 offers a mobile-first flexbox grid system that allows you to divide...

4 minutes read.

Bootstrap With CSS

← Prev Next → ...

1 minute read.

Bootstrap 4 Spinners

Bootstrap 4 offers spinner is a loading indicator that is used to display the loading state of any component or web page. The spinner is also known as a loader...

7 minutes 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 Form

Bootstrap 4 Forms Bootstrap 4 provides forms, which are one of the essential components for web pages and web applications. It is an input-based component, used to collect user data with the help of...

8 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 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 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 Searchable Dropdown Menu

Searchable Dropdown Menu When we click on the dropdown button/arrow in this dropdown menu, an input field will pop up with all the dropdown items listing inside. If we type in...

5 minutes read.

Text Shadows in CSS

Text shadows are created with the text-shadow CSS property. It takes a list of shadows separated by commas to be applied to the text and any of its styles. Each...

5 minutes read.