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

Library for adjusting the x axis scaling accurately

I need to find a JavaScript chart library that can support lines and zooming for handling a large amount of data. One issue I have encountered with other libraries is scaling the x-axis based on date and time data provided in strings: y=[43,56,34,63....] ...

Issue with integrating SQL and PHP/HTML using a web form

I've encountered some challenges while attempting to create a social network database, specifically with inserting values into the user_ table. The database setup is in place, but there are no updates happening (no output code when redirecting to PHP ...

Employ a for loop to generate custom shapes within the canvas

EDIT: I will be sharing all of my code including the HTML and JS. Pardon me for the abundance of comments. I am attempting to generate rectangles in a canvas using a for loop (taking user input) and then access them in another function to perform certain ...

Javascript data table pagination and custom attributes resulting in unexpected truncation of strings

Currently, I have implemented an Ajax functionality in my template to receive a JSON response and dynamically populate a datatable with the elements from that JSON: $('.bicam_tests').click(function(){ $.ajax({ type: 'GET', ...

Tips for scaling an image to perfectly fit the browser screen

I have spent a significant amount of time researching and coding, but I am still unable to get this seemingly trivial task to work. Here are the conditions: The browser window size is unknown, so any solution involving absolute pixel sizes will not work. ...

Adjust padding for smaller devices in React using Material UI

In my grid layout, I have columns set to 3,6,3 and a spacing of 3 between them. On larger screens, the spacing between grids looks fine. However, as the screen size decreases, the spacing remains the same which is not visually appealing. What I am aiming ...

Explore an illustration of a website with a hover effect

As I delve into the world of web development, I have taken up the challenge of replicating another website's layout to hone my skills. However, there is one aspect of this site that has me stumped =/ <div class="a"> <span>Teste</span&g ...

The results of running 'npm run dev' and 'npm run build prod' are different from each other

Currently, I am in the process of developing a progressive web app using Vue.js. During development, I utilize the command npm run dev to initiate the local server that serves the files over at http://localhost:8080/. When it comes time to build for produ ...

Is it a scope issue if ng-click is not firing and the function is not working properly?

I'm facing an issue with an animation that is not working as intended. The goal is to have the search button trigger an animation to pull a search bar from the right side, allowing users to input their search query. However, the ng-click function does ...

Instructions for utilizing the nav-pill with nav-justified components in Bootstrap3x without incorporating any responsive capabilities

I'm eager to incorporate this into my project : <div class="container"> <ul class="nav nav-pills nav-justified"> <li class="active"><a href="#">Home</a></li> <li><a href="#"> ...

Ways to assign a CSS class specifically for images

.calendarList { background-image: url('/resource3/hpsc/common/images/calendar.png'); background-position: 135px 50%; background-repeat: no-repeat; cursor:pointer; } <input type="text" id="toDatepicker" class="cal ...

How can I determine the width of a Bootstrap Column on a smartphone?

Currently, I am utilizing Photoshop to design a sequence of Wireframes for a forthcoming eCommerce website. I have a solid grasp on Bootstrap functioning based on a '12 column' structure, where the width of each column varies depending on the vi ...

implementing a delay after hovering over a CSS hover effect before activating it

I'm trying to achieve a specific effect using JavaScript or jQuery, but I'm struggling to figure it out. I have created a simple CSS box with a hover effect that changes the color. What I want is for the hover effect to persist for a set amount o ...

Having trouble getting your React project to work because NPM start won't cooperate? Here are some troubleshooting tips

Hello, I recently downloaded a React project from https://github.com/fabiau/jc-calendar. However, when I try to run npm start, I encounter error messages. I have attempted to use "NPM Fund" and "NPM Update", but unfortunately, neither of them resolved the ...

The React MUI v5 Card's background features a subtle white hue with a 5% opacity, leaving me curious about its origin

I've noticed a strange styling issue in my code. It seems to be related to a class called .css-18bsee0-MuiPaper-root-MuiCard-root, possibly from MUI's Card or MUI's Paper components. However, I can't find it in my own code. While tryin ...

Navigate through a filtered list of parent items with the use of cursor arrows in AngularJS

My form contains an input with a dropdown, where I display JSON data like this: { "title": "Parent #1", "child" : [ {"title": "Child ##1"}, {"title": "Child ##2"}, {"title": "Child ##3"}, {"title": "Child ##4"} ...

Get a webpage that generates a POST parameter through JavaScript and save it onto your device

After extensive research, I have hit a roadblock and desperately need help. My task involves downloading an HTML page by filling out a form with various data and submitting it to save the responses. Using Firebug, I can see that my data is sent over POST, ...

What techniques can I use to merge alpha channels with compositing in images?

Utilizing an HTML5 Canvas along with the KineticJS(KonvaJS) canvas library, I have successfully incorporated an Image element. My current objective is to erase specific pixels while maintaining a certain level of transparency. The red dot erases pixels at ...

Enabling the upload of .sql files in a file input field

I'm working on a file input field that I want to restrict to only accept XML, SQL, and text files. Here's the code snippet I have implemented so far: <input type="file" name="Input_SQL" id="Input_SQL" value="" accept="text/plain,application/x ...

Modify the JS/JQuery variable by utilizing the data entered into an HTML input field

I have implemented a javascript/ajax request on my advanced search page. <script> // window.setInterval(function() // { $(function () { var SearchTerm = '<?php echo $_POST['Search']; ...