Displaying JavaScript validation errors on a Bootstrap 4 .btn-group-toggle

I have created a star rating user interface using the Bootstrap 4 .btn-group.btn-group-toggle as shown in the code snippet below:

<div class="form-group">
    <div class="btn-group btn-group-toggle" data-toggle="buttons" aria-label="Rate this">
        <label class="btn btn-dark btn-sm">
            <input type="radio" name="rating" value="1" required> 1
        </label>
        <label class="btn btn-dark btn-sm">
            <input type="radio" name="rating" value="2" required> 2
        </label>
        <label class="btn btn-dark btn-sm">
            <input type="radio" name="rating" value="3" required> 3
        </label>
        <label class="btn btn-dark btn-sm">
            <input type="radio" name="rating" value="4" required> 4
        </label>
        <label class="btn btn-dark btn-sm">
            <input type="radio" name="rating" value="5" required> 5
        </label>
    </div>
    <div class="invalid-feedback">
        Please rate the item on a scale of 5
    </div>
</div>

Unfortunately, the validation error is not visible when a rating is not provided. I am utilizing the HTML5 default validation method suggested by Bootstrap 4 and implemented with JavaScript.

Is there a way to display a validation error for the .btn-group-toggle element?

Answer №1

When it comes to displaying custom validation messages in Bootstrap 4, there is a specific rule that needs to be followed:

.was-validated .form-control:invalid ~ .invalid-feedback,
.was-validated .form-control:invalid ~ .invalid-tooltip,
.form-control.is-invalid ~ .invalid-feedback,
.form-control.is-invalid ~ .invalid-tooltip {
    display: block;
}

The CSS sibling combinator ~ comes into play here, but it only works when the validation error element is a direct sibling of the input field as shown below:

<input type="text" class="form-control" required>
<div class="invalid-feedback">
    The text field is mandatory
</div>

In my scenario, the radio buttons within the form are nested deeper than the .invalid-feedback. To handle this, I incorporated additional code utilizing the HTML5 JavaScript API:

// ...
if (form.checkValidity() === false) {
    event.preventDefault();
    event.stopPropagation();

    var theRadio = form.querySelector('input[type=radio]');
    if (theRadio.checkValidity() === false) {
        theRadio.parentNode.parentNode.classList.add('group-invalid');
    } else {
        theRadio.parentNode.parentNode.classList.remove('group-invalid');
    }
}
// ...

This piece of code adds the class .invalid-group to the surrounding .btn-group by traversing up the DOM tree using .parentNode.parentNode (twice), allowing for customized styling:

.was-validated .group-invalid + .invalid-feedback {
    display: block;
}

With this approach, the validation error message will show up and persist until the form is submitted again, even after correction.

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

When invoking the Angular function to make an HTTP request, it will generate a recurring loop

When trying to call a function in mg-repeat that makes an HTTP request with an ID to find a list of data, I encountered an error message. Here is the function call: <div ng-repeat="ListeReponse in reponsefonction(Listechamps.keyQuestion)" > < ...

What is the best way to conceal an element by clicking anywhere other than on the element itself?

Currently, I am utilizing jQuery's toggle method to display or hide a page element when another specific page element is clicked. jQuery('a#mobile-search-icon).click(function(){ jQuery('#searchBox').toggle('slow'); }); ...

Identifying numerous array positions within a canvas

Greetings fellow developers, Today, I have an inquiry regarding a project I am working on, akin to a Tower Defense game created using canvas. I am facing a challenge in detecting multiple circles in one coordinate. Here's an excerpt of my current dil ...

Strange behavior of Jquery

I've run into a bit of confusion regarding how JQuery is behaving. Initially, I expected to see the results fname and zetest pop up on alert. Unfortunately, I'm getting unexpected outcomes. Could it be that I've missed something along the wa ...

How can you achieve a seamless or infinite scrolling effect on a webpage?

My idea is as follows: Imagine a long web page where, instead of the scrolling coming to an abrupt stop when the user reaches the end, I want the page to reload from the bottom and allow the scrolling to continue seamlessly. Specifics Picture this - as ...

JavaScript array loading failed for the C# web service

I am encountering an issue with a JavaScript object in my application that contains an array object, which is a collection of objects with two properties (Name, Value) on the server-side. Despite my efforts, when the code reaches the C# web service, the C ...

Trouble arises when attempting to add an image to a spherical object

I've searched through various threads, Googled extensively, watched YouTube tutorials.... But I can't seem to figure out how to apply a texture to my Sphere. When I run this code, all I see is a white Sphere without any texture showing up. Can so ...

Troubleshooting a misformatted JSON string that lacks proper double quotes in Java Script

{ DataError: { user_id: [ [Object] ] } } I want to transform this string into JSON structure like below: { "DataError": { "user_id": [ [Object] ] } } Is there a potential method to achieve this outcome from incorrectly formatted JSON string? ...

Experiencing a RepositoryNotFoundError in TypeORM, although I am confident that the repositories are properly registered

I am creating a new application using Next.js + TypeORM and encountering an issue with the integration. RepositoryNotFoundError: No repository for "User" was found. It seems like this entity is not registered in the current "default" connection? Althoug ...

In what ways can I enhance and visually improve JSON data using a jquery/javascript plugin?

My current project requires me to display JSON data received from the backend in a textarea. However, the data comes unformatted and not validated. Now I'm facing two main challenges: 1) How can I beautify the JSON content in the textarea? 2) How can ...

What is the process for creating an Account SAS token for Azure Storage?

My goal is to have access to all containers and blobs in storage. The Account SAS token will be generated server-side within my Node.js code, and the client will obtain it by calling the API I created. While Azure Shell allows manual creation of a SAS toke ...

Show a loading image after clicking on an image or button using JavaScript

I recently created an App using PhoneGap and JqueryMobile. Transitioning between multiple HTML pages by clicking on images seems to be causing slow loading times, leaving end users unaware of what's happening in the background. I am looking for a way ...

Decoding Lodash: Unveiling the findwhere and copy operator in the realm of

Could someone please explain why using Lodash to fetch an object with findWhere allows for a reference copy that enables dynamic changes based on user actions, while the same operation using the copy operator fails to update the source object? I have creat ...

Most effective method for streamlining conditional checks in JavaScript

To enhance the quality of my code and improve its readability, I have decided to implement a currying functions approach and create pure helper functions for repetitive code snippets. One issue I noticed was the frequent existence/type checks throughout my ...

Trouble with Webpack compiling SCSS files

I'm struggling with setting up webpack to bundle my js react components, js modules, and compile my .SCSS files to css. Despite multiple attempts, I keep encountering errors. Below is an excerpt from my webpack.config.js: const webpack = require(&a ...

javascript: revealing the identity of a click event handler

Here I am looking to create a click function with a specific name and parameters for the purpose of code reusability. This will allow me to write one generic function that can be used for common tasks like enabling users to delete various types of data. I ...

What could be causing the jQuery spritely animation to display an additional frame upon the second mouseenter event?

I have been experimenting with CSS sprites and the jQuery plugin called spritely. My goal is to create a rollover animation using a Super Mario image. When the mouse hovers over the Super Mario <div>, I want the animation to play forward. And when t ...

``I am experiencing difficulties with utilizing a personalized color scheme in React JS with Material

I'm currently working on customizing the color palette for my project, but I am only able to modify the main attribute and not others. My development environment is JavaScript with MUI, not Typescript. import './App.css'; import {BrowserRout ...

Removing solely the selected item, leaving the rest of the elements on the canvas untouched

Just starting out with coding and working on a game for a school project. The idea is to have random circles or "targets" appear on the screen, and the user has to click them. I've been struggling with keeping the "un-clicked" circles on the canvas wh ...

The callback function in jQuery does not function properly in a custom class or object

Hello, I am new to the world of programming so bear with me if this question seems basic. I am currently working on creating a simple wave effect to give the illusion of moving water. Initially, I achieved this using a straightforward jQuery function which ...