Enhancing user experience by highlighting invalid input fields with a red border using client-side HTML5 validation and Bootstrap 5.2

When reviewing the Bootstrap 5.2 validation documentation,

https://getbootstrap.com/docs/5.2/forms/validation/

"It has come to our attention that the client-side custom validation styles and tooltips are not accessible at this time, as they are not exposed to assistive technologies. While we are actively working on a solution for this issue, in the meantime, we suggest either utilizing the server-side option or sticking with the default browser validation method.",

I've been exploring other methods to apply styling to invalid input fields with a red border. I attempted the HTML5 approach but have been unsuccessful in getting a red border to show up. In the past, it was straightforward to achieve this using Bootstrap 3.3.7, but now, after years have passed, I am struggling to make it work with Bootstrap 5.2 (or any framework).

<html lang="en-us">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Favorite fruit with required attribute</title>
    <style>
        input:valid {
            border: 2px solid green;
        }
        
        input:invalid {
            border: 2px solid red;
        }
        
        input:invalid:required {
            background-color: #d2d2d2;
        }
    </style>
</head>

<body>
    <form>
        <div>
            <label for="choose1">What is your favorite color?</label>
            <input id="choose1" required>
        </div>
        <div>
            <label for="choose2">What is your favorite breakfast food?</label>
            <input id="choose2" required>
        </div>
        <button>Submit</button>
    </form>
</body>

</html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Favorite fruit with required attribute</title>
    <style>
        input:valid {
            border: 2px solid green;
        }
        
        input:invalid {
            border: 2px solid red;
        }
        
        input:invalid:required {
            background-color: #d2d2d2;
        }
    </style>
</head>

<body>
    <form>
        <div>
            <label for="choose1">What is your favorite color?</label>
            <input id="choose1" required>
        </div>
        <div>
            <label for="choose2">What is your favorite breakfast food?</label>
            <input id="choose2" required>
        </div>
        <button>Submit</button>
    </form>
</body>

</html>

Answer №1

Have you tried using this Javascript code snippet? If you find that you don't need to send any data from the form, simply remove the type="submit" attribute from the button element and change the event listener from "submit" to "click".

//Execute when DOM is fully loaded
window.addEventListener('DOMContentLoaded', () => {
  //Get the form by its ID
  const form = document.getElementById("formm");
  //Check form validity on submission
  form.addEventListener("submit", (e)=>{
    if (form.checkValidity() === false) {
      e.preventDefault();
      e.stopPropagation();
    }
    form.classList.add("was-validated");
  })
});
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Favorite fruit with required attribute</title>
    <!--Bootstrap CSS-->
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c0e0303181f181e0d1c2c59425e425e">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
</head>

<body>
<!--add an ID and "novalidate" to disable the alert from browser-->
    <form id="formm" novalidate>
        <div>
            <label for="choose1">What is your favorite color?</label>
            <input class="form-control" id="choose1" required>
        </div>
        <div>
            <label for="choose2">What is your favorite breakfast food?</label>
            <input class="form-control" id="choose2" required>
        </div>
        <!--add button type to submit-->
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
    <!--Just Bootstrap JS-->
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6b0904041f181f190a1b2b5e45594559">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>

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

What are the steps to incorporating the League Gothic font into my website design?

Is there a way to incorporate League Gothic font into my website design? Visit the League Gothic GitHub repository Appreciate any guidance on this matter, ...

I am experiencing issues with the detection of mouseover events on an SVG circle

I am currently working on a d3 map with zoom functionality that displays circles representing different cities. However, I am facing an issue where the mouseover event for the circles (which shows tooltips and clicking reveals some lines) seems to only reg ...

Center-align text so it is perfectly centered over an image

Looking for help with aligning text in social media images? Currently, the text is positioned at the bottom of each image. Check out this example: http://jsfiddle.net/uT4Ey/ CSS: .img { background-color: red; height: 3em; width: 3em; display: inl ...

Creating interactive <td> elements in HTML with JavaScript editor capabilities

Currently, I am working on creating an editable table feature and managed to find a good example to follow. However, I have encountered some issues along the way. <td contenteditable="true" class="hover" onBlur="saveToDatabase(this,'question' ...

Searching for the precise draggable grid line position in rulerguides.js - tips and tricks!

Currently, I am utilizing rulerguides.js in my project. I have customized it for a specific div to display rulers and grid lines. You can refer to this FIDDLE. The rulers are functioning properly, but the draggable grid lines are being calculated based on ...

Guide to positioning a div in the center while implementing animations through transition and transformation using scale

Creating a popup for my React app without relying on external libraries is my current project. I am experimenting with using transition and transform with scale to size the popup dynamically based on screen size and content, then center it on the screen. ...

The directive for Content Security Policy in Django framework

I am having trouble importing font-awesome into my application. I've tried the following code: <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> However, this is causing an err ...

What is the best way to align elements in relation to a central div container?

Is there a way to align two buttons in the center on the same line, and then position a selector to the right of those centered buttons? How can I achieve this arrangement? Essentially, how do you position an element in relation to a centered div? UPDATE: ...

The Safari browser is having trouble rendering the website's CSS and HTML properly

Check out this example of how the website should look on Chrome for Android: https://i.stack.imgur.com/RzUSp.jpg And here is an example from Safari on iPad Mini 2: https://i.stack.imgur.com/PAj2i.jpg The Safari version doesn't display the proper fon ...

Is there a way to utilize an Angular Material checkbox without any extra gaps or spacing?

Currently, I am working with Angular Material and trying to figure out how to remove the default spacing around the checkbox. The checkboxes in Angular Material are typically surrounded by some space (as shown in the image). Is there a simple way to elimin ...

The $_REQUEST variable is functioning properly, while the $_POST variable seems to

I currently have an HTML form using the post method. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type='text/javascript& ...

Verify whether the value is in the negative range and implement CSS styling in React JS

I have been developing a ReactJS website where I utilize Axios to fetch prices from an API. After successfully implementing this feature, I am now looking for a way to visually indicate if the 24-hour change percentage is positive by showing it in green, a ...

What is the best way to shift a text element within the footer section?

I have arranged two columns within the container, but I am looking to position the .company and .copyright text at the bottom left of the footer column. The Follow Us heading should be on the right side with the .justify-text below it, followed by social m ...

jQuery: Set default option selected or reset value

I'm attempting to change the value of the nearest select option dynamically. $(document).ready(function () { $('.limitation_points').hide(); $('.field .limitSelected').each(function () { $(this).change(function ( ...

What is the best way to dynamically convert a lodash object (specifically a filter object) into jQuery's listview component?

After referencing the answer to this topic as my first step, which can be found here, my next goal is to utilize a filter function to retrieve all matching entries from a JSON file based on a search term. The objective is to loop through each match and con ...

Image overlay fading effect with text appearing once the image fades

After exploring various hover effects and techniques to display text on hover, I still haven't found the answer to my specific question. My goal is to have an image with a transparent overlay that fades out on hover, revealing text in its place. It s ...

Renaming file names for Bootstrap 4.5 demonstrations

Trying to utilize a Bootstrap 4.5 example, but running into issues when renaming the HTML or CSS files - it breaks the formatting link for the page. Is there a way to duplicate the original example files and modify the names (such as "my_page.html" or "m ...

What are the ways to ensure my query columns fill the entire page space?

Currently, when I execute a query, it retrieves the correct information. However, I want to make my columns span across the entire page instead of being centered in the middle with empty space on the sides. Is there a way to expand the columns? Below is t ...

Creating a captivating animation for a social media like button with CSS

I came across some animation code on the web and noticed that when I click the image, it replays the animation from the starting point. I want to make it so that when I click the image, the animation plays and stops, and if clicked again, resets the image. ...

I am interested in updating the color of the navigation bar displayed on this website

I am having some trouble with manipulating the appearance of - Specifically, I'm struggling to change the color of the black bar at the top to blue. I have scoured the CSS files and examined the HTML, but I can't seem to locate the relevant code ...