Utilizing the default validation in Bootstrap 4 to ensure proper email format in form submissions

Can anyone assist with validating an email form field using Bootstrap 4 without the need for any additional libraries? I believe it might require a simple JavaScript function at the end of the document to check if the fields match. Any guidance on this matter would be greatly appreciated. It's surprising that this feature isn't already available or documented on the official Bootstrap website, considering it seems like a common requirement.

<!DOCTYPE html>
<html>

<head>
  <title>Email Validation with Bootstrap 4</title>
  <?php
echo '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">';
?>
</head>

<body>
  <form class="needs-validation" novalidate>
    <div class="form-row">
      <div class="col-md-4 mb-3">
        <label for="validationCustom01">Email</label>
        <input type="email" class="form-control" id="email" placeholder="Email" required>
        <div class="valid-feedback">
          Looks good!
        </div>
      </div>
      <div class="col-md-4 mb-3">
        <label for="validationCustom02">Confirm Email</label>
        <input type="email" class="form-control" id="confirm_email" placeholder="Confirm Email" required>
        <div class="valid-feedback">
          Emails should match
        </div>
      </div>
    </div>

    <div class="form-group">
      <div class="form-check">
        <input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
        <label class="form-check-label" for="invalidCheck">
      Agree to terms and conditions
    </label>
        <div class="invalid-feedback">
          You must agree before submitting.
        </div>
      </div>
    </div>
    <button class="btn btn-primary" type="submit">Submit form</button>
  </form>

  <script>
    // Example starter JavaScript for disabling form submissions if there are invalid fields
    (function() {
      'use strict';
      window.addEventListener('load', function() {
        // Fetch all the forms we want to apply custom Bootstrap validation styles to
        var forms = document.getElementsByClassName('needs-validation');

        // check match

        // Loop over them and prevent submission
        var validation = Array.prototype.filter.call(forms, function(form) {
          form.addEventListener('submit', function(event) {
            if (form.checkValidity() === false) {
              event.preventDefault();
              event.stopPropagation();
            }
            form.classList.add('was-validated');
          }, false);
        });
      }, false);
    })();
  </script>
</body>

</html>

Answer №1

Ensure you are using all the links correctly... it will work

// Sample starter JavaScript code for disabling form submissions when there are invalid fields
    (function() {
      'use strict';
      window.addEventListener('load', function() {
        // Grab all the forms we want to apply custom Bootstrap validation styles to
        var forms = document.getElementsByClassName('needs-validation');

        // check match

        // Iterate over them and prevent submission
        var validation = Array.prototype.filter.call(forms, function(form) {
          form.addEventListener('submit', function(event) {
            if (form.checkValidity() === false) {
              event.preventDefault();
              event.stopPropagation();
            }
            var email = $("#email").val();
            var confirmemail = $("#confirm_email").val();
            if(email !== confirmemail){ 
            form.classList.add('was-validated');
              $("#validate").html("Email Should Match");
              $("#validate").addClass("error");
               $("#confirm_email").addClass("error-text");
              event.preventDefault();
              event.stopPropagation();              
            }
            else{
            $("#validate").removeClass("error");
            form.classList.add('was-validated');
               $("#confirm_email").removeClass("error-text");
              $("#validate").html("Looks Good!");
            }
           
          }, false);
        });
      }, false);
    })();
.error{
color:red !important;
}
.error-text{
border:1px solid red !important;
}
<!DOCTYPE html>
<html>

<head>
  <title>JQuery-validation demo | Bootstrap</title>
  <!--<?php
echo '<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">';
?>-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>

<body>
  <form class="needs-validation" novalidate>
    <div class="form-row">
      <div class="col-md-4 mb-3">
        <label for="validationCustom01">Email</label>
        <input type="Email" class="form-control" id="email" placeholder="Email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" required>
        <div class="valid-feedback">
          Looks good!
        </div>
      </div>
      <div class="col-md-4 mb-3">
        <label for="validationCustom02">Confirm Email</label>
        <input type="email" class="form-control" id="confirm_email" placeholder="Confirm Email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" required>
       
        <div id="validate" class="valid-feedback">
          Emails should match
        </div>
      </div>
    </div>

    <div class="form-group">
      <div class="form-check">
        <input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
        <label class="form-check-label" for="invalidCheck">
      Agree to terms and conditions
    </label>
        <div class="invalid-feedback">
          You must agree before submitting.
        </div>
      </div>
    </div>
    <button class="btn btn-primary" type="submit">Submit form</button>
  </form>
</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message: Iframe chrome encountered a Uncaught DOMException when attempting to access the 'localStorage' property from 'Window': Document does not have permission

I recently developed a JavaScript widget that utilizes localstorage to set and retrieve properties of the window. Upon opening this widget in Chrome, I encountered an error message: Uncaught DOMException: Failed to read the 'localStorage' prop ...

Run a series of Mocha unit tests based on the outcomes of previous test results

Currently, I am in the process of writing unit tests for a NodeJS application that I am developing. In relation to some unit-testing logic, I have a question. Imagine if the application first creates a "Group" for users, followed by creating individual Us ...

Divergence in Angular cookies values observed when accessed from various URLs

Currently, I am utilizing Angular cookies to store information. This is how I include information. oItems represents the JavaScript array of objects. Angular Version 1.4.7 $cookies.putObject("oItems", oItems, [{path: '/', expires: exp, domain ...

Ways to activate onChange multiple times for a single item within material ui's autocomplete feature

I am utilizing the autocomplete component in the Material UI. Upon selecting an item, the onChange props are triggered and certain actions are performed. However, I am encountering an issue where I can select the same object multiple times without the on ...

Update text displayed on radio button selection using jQuery

Is there a way to change the label text on a selected radio button from "Set default" to just "default" using jQuery? I think I need to use the class radio-default as the selector, but I'm not very familiar with jQuery. <div class="radio-default ...

Rendering a component and updating state with inline onClick event handlers

When discussing the concept of pure render methods in React and highlighting the serious anti-pattern of setting state inside the render function, how strictly should this be adhered to? It is understood that triggering a setState within the render functio ...

What is the best way to make an element unclickable on an HTML page while still making it draggable using jQuery's draggable

One way to create an element on a page with a mouse click is by using the following code: $("#sheet").append('<input class="elements" id="Button12" type="button" value="button" />'); If you want the element to be temporarily unclickable, ...

The variable is unable to be accessed within the PHP function query

After passing a variable through ajax to a function within my php file "Cart_code.php", I encountered an issue where the variable was not accessible inside the function. Can you help me figure out why? Javascript $.ajax({ type: "POST", url: "incl ...

What is the proper way to invoke a child method after converting an object from a parent class to a child class?

When we have a subclass B that overrides a method from its superclass A in TypeScript, why does calling the method on an instance of A result in the parent class's implementation being called? In TypeScript, consider a class called Drug with properti ...

Am I making a mistake in my implementation of sending Socket.io messages to a designated room?

Upon a user joining, I alter their ID to a shortened random code. This change is made to utilize the id as a visible session ID on the front-end. I mention this to prevent confusion regarding non-standard socket IDs and their relation to potential issues. ...

Combining Jquery scripts for seamless integration

I am facing an issue while trying to execute two different jQuery scripts simultaneously - one named balancedgallery and the other museum. Individually, each script works perfectly fine. However, when running them together, the balancedgallery script seems ...

extracting a particular value from a JSON object using JavaScript

How can I extract a specific value from my JSON file using Node.js? var request = require("request"); var options = { method: "GET", url: "URL of my database", headers: { "cache-control": "no-cache&qu ...

Execute the knockout function using jQuery

There's a scenario where I am trying to trigger a knockout method using jQuery. The Knockout viewModel has already been bound, but I'm unsure of how to call it using jQuery. Below is the snippet of my code: $(document).ready() { form_submit( ...

You are unable to utilize ScrollView within BottomSheet in React Native

After developing a search feature and page in my app, I encountered an issue with displaying content in BottomSheets. Despite using a DataTable, I found that a ScrollView cannot be nested inside the BottomSheet, resulting in not all content fitting vertica ...

Navigating the intricacies of sub-State mapping in Nuxtjs

I have set up a state called ~/store/modules/general/index.js Within this state, there are Actions named get_info and get_pages, as well as states named info and pages. When I use ...mapActions({ getInfo: 'modules/general/get_info' getPages: ...

Struggling to retrieve the session value using JavaScript in a C# application

Currently, I am attempting to retrieve four values from the session. However, I am only able to fetch two of them, while the other two seem to be missing. As a beginner, I apologize if my question comes across as too simplistic. Within a tree view, I have ...

Struggling to synchronize animation timing between elements using jquery

When you navigate to an album (for example, Nature because I'm still working on the others) and select one of the images, they all gradually fade out while the selected image appears on the screen. What's actually happening is that the selected i ...

Adjusting the gap between TableRows in Material-UI

Is there a way to increase the spacing between TableRow MaterialUI components in my code? <S.MainTable> <TableBody> {rows.map(row => { return ( <S.StyledTableRow key={row.id}> <TableCell component="th" s ...

Strategies for resolving a mix of different data types within a single parameter

Here, I am setting up the options params to accept a value that can either be a single string or another object like options?: string[] | IServiceDetail[] | IServiceAccordion[]; However, when attempting to map these objects, an error is encountered: Prope ...

Using Handlebars JS to incorporate HTML tags such as <li>, <br>, and more in your data

Is there a way to use handlebars to display a list of data in an unordered format, with "title" and "articles" as the main categories? The issue arises when some of the articles contain HTML tags, such as <a> for links. In my current code, instead of ...