Issue with form validation in Bootstrap 5.2 JavaScript implementation

I'm having trouble with my client-side form validation not working properly before the server-side validation kicks in. I've implemented Bootstrap 5.2 and followed the documentation by adding needs-validation and novalidate to the form.

Scenario:

When I enter a title that exceeds 50 characters in the event_name input field, which has a max=50 set, the invalid-feedback does not appear, and the form gets submitted despite failing the validation only to be caught by the server-side validation later.

Question:

Why is the client-side validation not taking effect?

Form:

<% layout('layouts/boilerplate') %>

<div class="row">
    <h1 class="text-center">Setup</h1>
    <div class="col-xl-8 offset-xl-2">
        <form action="/events/new" method="POST" class="needs-validation" novalidate>
            <h5 class="mt-2">Activation setup</h5>
            <hr>
            <label for="event[promotion_type]">Select which of your qr codes you'll use for this event</label>
            <div class="btn-group-lg my-4 d-flex flex-wrap justify-content-center" role="group"
                aria-label="Basic radio toggle button group" required>
                <% for (let q of qr) { %>
                    <input type="radio" class="btn-check" onselect="setQrName" name="event[qr_name]" value="<%= q.name %>"
                        id="<%= q.name %>" autocomplete="off">
                    <label class="btn btn-outline-primary m-2" for="<%= q.name %>">
                        <%= q.name %>
                    </label>
                    <% } %>
            </div>
            <div class="invalid-feedback">
                You must select a QR code
            </div>
            <small class="form-text text-muted">*Do not select a qr code that's mapped to another
                activation. Manage qr codes on the <a href="/users/<%= user.id %>/activations">activations
                    page</a>.
            </small>

            <div class="row flex-row d-flex" style="margin-top: 4em;">
                <div class="mb-2 col-6">
                    <label class=" form-label" for="event[event_start]">Start date & time*</label>
                    <input class="form-control" type="datetime-local" onchange="timeCheck()" id="eventStart"
                        name="event[event_start]" required>
                    <div class="invalid-feedback">
                        Must be filled out
                    </div>
                </div>
                <div class="mb-2 col-6">
                    <label class="form-label" for="event[event_end]">End date & time*</label>
                    <input class="form-control" type="datetime-local" onchange="timeCheck()" id="eventEnd"
                        name="event[event_end]" required>
                    <div class="invalid-feedback">
                        Must be filled out
                    </div>
                </div>
                <p id="timeValidate" style="color: red; font-style: italic;">
                    <%= %>
                </p>
            </div>

            <div class="my-3">
                <div class="mb-3">
                    <label class="form-label fw-medium" for="event_name">Activation title*</label>
                    <input class="form-control" placeholder='Ex, "Win 50% off!" or "1 in 10 win a free hat!"'
                        maxlength="50" type="text" id="event[event_name]" name="event[event_name]" required>
                    <div class="invalid-feedback">
                        Must be filled out
                    </div>
                    <small class="my-2">A short title that will get people excited to participate</small>
                </div>
                <div class="mb-3">
                    <button class="btn btn-primary"
                        onclick="update(document.getElementById('eventStart').value,document.getElementById('eventEnd').value)">Next</button>
                </div>
        </form>
        <a href="/events">Back to all events</a>
    </div>
</div>

Javascript validation from boilerplate.ejs

        <script>
            (function () {
                'use strict'

                // Fetch all the forms we want to apply custom Bootstrap validation styles to
                var forms = document.querySelectorAll('.needs-validation')

                // Loop over them and prevent submission
                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>

Note:

As mentioned by @carolskelly in the comments, the required validation still functions correctly preventing the submission of blank input fields.

Answer №1

As per the information provided in the Documentation on Bootstrap 5.2 Validation:

The current issue seems to be related to the lack of accessibility for client-side custom validation styles and tooltips, as they are not accessible to assistive technologies. While a solution is being worked on, it is recommended to consider using either the server-side option or default browser validation method.

Is it possible that this is causing the problem you are currently facing?

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 is the best method for implementing a Twitch <script> tag within Vue.js?

In an effort to replicate the functionality I achieved in Angular here, I am now attempting to do so within Vue.JS (2.6+). My goal is to utilize the Twitch API for embedding a Stream, which currently only offers usage through inline HTML: <script src= ...

Unpredictable Behavior of CSS Transition with JS createElement() Function

I'm using JavaScript to create a div element and I'm adding the CSS property transition: .5s linear top; When the user clicks on the element (onmousedown event), it is supposed to smoothly move to the top of the screen and then be deleted using ...

Determine the central x and y coordinates of elements depending on the specified screen dimensions

Is it possible to determine the center position of an element at a specific screen size using jQuery? I am looking to calculate the center position of an element based on provided height and width dimensions. For instance, if I provide the screen size (1 ...

having trouble with changing the button's background color via toggle

I've been experimenting with toggling the background color of a button, similar to how changing the margin works. For some reason, the margin toggles correctly but the button's color doesn't. <script> let myBtn = document.querySele ...

.bail() function does not function properly when used in conjunction with express-validator

While registering a new user, I require their name, email, and password. If no name is provided, there is no need for the backend to validate the email. I believe that the use of .bail() in express-validator should handle this situation, but unfortunately ...

Create a substitute for Object.seal, Object.freeze, and Object.preventExtensions applications

Is there a way to freeze an object's existing properties while still allowing new ones to be added? I can't seem to find any built-in functionality for Object.freezeExisting(), so maybe it's worth considering implementing it, possibly even w ...

Best approach for retrieving and adding a large number of images when dealing with slower connections

Currently, I am retrieving 100-200 images using a combination of ajax-php-mongodb. The process involves ajax making an initial call with parameters, php on the server side locating the appropriate mongo document containing all image file ids in grid fs, fe ...

Consistently Incorrect Date Formatting in Bootstrap Display

I have a potential issue with my date display. It should show a default "Start Date" in a short date format, but when the "Sale Date" DropDownBoxFor is toggled, it should display an AJAX result date. However, the display always appears in a date and time f ...

The components declared in the index file are rendered on every route throughout the React application

I'm a beginner with React and I'm using react-router version 6.0.2. My issue is that I created a component for the router and then called this component in the index file. However, when I add another component to the index file, it gets rendered ...

The scroll function is failing to activate at the desired location

I've been trying to fine-tune a window scroll function I created. Initially, I attempted to use waypoints for this, but unfortunately, I couldn't get it to work as expected. The main issue I'm facing is that the function triggers too early ...

Enhance Your jQuery Skills: Dynamically Apply Classes Based on URL Like a Pro!

Here is an example of HTML code for a progress meter: <div class="col-md-3" style="margin-left: -20px;"> <div class="progress-pos active" id="progess-1"> <div class="progress-pos-inner"> Login </div> </di ...

Dependencies in AngularJS factories

I'm currently using AngularJS to extract data from mongodb. I have been attempting to utilize a factory to retrieve this information through the $http method. Despite researching and trying numerous approaches, none seem to work for me. In addition t ...

Is it possible to line up Ajax request in Javascript?

I am seeking a way to schedule an Ajax request to occur every second. The code I currently have in place functions flawlessly. window.onload = function () { setTimeout(doStuff, 1000); // Wait before continuing } function doStuff() { ...

Unfulfilled expectation of a promise within an array slipping through the cracks of a for loop

I have a function that generates a Promise. Afterward, I have another function that constructs an array of these promises for future utilization. It is important to note that I do not want to execute the promises within the array building function since so ...

Trigger the execution of the second function upon the successful completion of the first

In the following code, my concept is to display: The clicked kingdom (clicked_id) initiates an attack on (clicked_id). https://i.stack.imgur.com/Bx8QW.png https://i.stack.imgur.com/Cg2GL.png https://i.stack.imgur.com/gUNxM.png How can I trigger the sec ...

Understanding the process of unmarshalling an array within a POST request

I am attempting to send an array of JSON data with a POST request to an API server. However, I keep encountering the following error: cannot unmarshal array into Go value of type models.UserRequest Despite trying to unmarshal the data using a factory and ...

Sending a variable to an AngularJS factory

I am currently working on a select list that looks like this: <select name="make" class="form-control" ng-model="selectCity"> <option value="Kannur">Kannur</option> <option value="Agra">Agra</option> <option va ...

Incorporate new content into a jquery mobile listview on the fly

I'm attempting to use JavaScript to dynamically populate a listview with items. Here is the code I have written: //Function to load data fields for items dynamically function initialiseFields(listViewId){ for(var i = 0; i < 10; i++){ ...

Adding an external font with CSS in Bootstrap 5 can be quite challenging

Hey there, I'm a newcomer around here and I could use some help with my post. It might not be perfect, but any guidance you can offer would be appreciated. The issue I'm facing is that I'm having trouble getting the font I downloaded or lin ...

Retrieve the specific data from the database when the <tr> element is hovered over

Hey everyone, I've been struggling with a problem for some time now. I have a loop that retrieves values from a database and I want each value to display onmouseover using JavaScript. However, it's only showing the value of the first row for all ...