Issue with Vanilla JS form validation in Bootstrap 4

I successfully created a script to validate my Bootstrap 4 form, but I'm facing an issue where the error message is replacing the input field. Should I pursue validating BS4 with Vanilla JS or stick to using Bootstrap validation? What's the industry best practice for this scenario? This is my first time working on form validation.

Check out the fiddle here:

https://jsfiddle.net/wunrsjdy/

HTML:

          <div class="container">
            <div id="form">
              <h1 class="page-title">Want To Be Our Client? Fill Out the Questionnaire Below</h1>



              <form id="form-user" action ="#" method="POST">
                <div class="form-group" id='errorTeste'>
                  <label for="name">Company Name</label>
                  <input type="text" class="form-control" id="name" name= "name" placeholder="">
                </div>

                <button type="submit" class="btn btn-primary" id="button-send">Submit</button>
                </form>


            </div>


JS

const name = document.getElementById('name')
const form = document.getElementById('form-user')
const errorElement = document.getElementById('errorTeste')

form.addEventListener('submit', (e) => {
    let messages = []
    if (name.value === '' || name.value == null) {
        messages.push('Please enter your company name.')
    }

    if (messages.length > 0) {

    e.preventDefault()
    errorElement.innerText = messages.join(', ')
    }
})

Answer №1

Within your code snippet, the innerText attribute of errorElement is being modified. Interestingly, errorElement is linked to your .form-group element:

const errorElement = document.getElementById('errorTeste')

// Further down in your html...
<div class="form-group" id='errorTeste'>

It seems that updating the inner text of .form-group may cause the input and label elements within it to be replaced.

Your approach shows promise. Consider displaying a separate element with a styled error or warning message when user input is invalid by utilizing the element's style.display attribute. Perhaps there was a mix-up where you accidentally assigned the #errorTeste id to the wrong element, like the .form-group? Just a thought.

For reference, here's an example demonstrating how you could enhance the visual appeal:

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

If the socket cannot be found, an error callback will be activated

Below is the method I am using to send a message to a targeted socket connection. socket.broadcast.to(socketid).emit('message', JSON.stringify(data)); If the specified "socketid" does not exist, is there a mechanism in place to capture the erro ...

how to reorganize page sections using javascript

Hello, I am new to HTML5 and Javascript and I am trying to create a simple function that swaps the positions of two sections using an event trigger. The first function works fine, moving the section with ID "con" to the top. However, the second function i ...

What is the best way to emphasize an element on a webpage with Selenium and Python?

Recently, I inherited an existing selenium framework that utilizes Python for scripting. In order to aid in debugging and other tasks, I am interested in implementing a feature that highlights the element currently being acted upon (such as an input box, l ...

Repeated information in HTML tables

I am currently working with two HTML tables and two sets of JSON data. Initially, I load one table with the tableData which has a default quantity of 0. In my HTML form, there are three buttons - save, load draft, and edit. Upon clicking on load draft, I p ...

Error: The specified object does not contain the 'tableRow' method

I am currently working on a contacts book project and I need a table to update as the user inputs data. However, I keep encountering an error related to 'tableRow'. I have tried changing function names and other solutions but haven't been ab ...

What is the best method for accessing the properties of a JavaScript object based on input from a textbox?

Just starting out with angular and having trouble generating or updating a table based on text boxes. The schema includes country, sales, and profit fields. There are two text boxes for the x-axis and y-axis inputs. The table should dynamically update when ...

An effective way to connect the ng-model of a <select> element with ng-options within an ng-repeat loop

My task list consists of: [{ Title: "Title1", Position: "9" },{ Title: "Title2", Position: "1" },{ Title: "Title3", Position: "5" },{ Title: "Title4", Position: "7" }] I am attempting to generate a series of <select> ...

Error loading QR code column in HTML table on tablet device

I am working on a pharmacy application that displays a HTML table with QRcodes as one of its column values. I am using the QRcode.min js library to convert the string to QRcode. json = $.parseJSON(JSON.stringify(res.d)); // console.log('data ' ...

Issues with the count up functionality in jQuery

I'm currently working on a project involving countups. My aim is to have multiple countups displayed on a single page. While having one countup using interval() function poses no issues, I encounter trouble when trying to display two or more countups ...

The style from '<URL>' was not applied as it has a MIME type of 'text/html', which is not a compatible stylesheet MIME type

After attempting to run the angular application with the home component, an error appeared stating that styles were refused and images could not be found. It's puzzling because the CSS and image folder are located in the /src/assets folder. I have tr ...

leveraging the dispatch instance of the redux store as opposed to including dispatch as a parameter

When discussing the change in how dispatch is passed into middleware in the documentation, Dan doesn't provide much explanation. He simply states: But there's also a different way to enable chaining. The middleware could accept the next() di ...

The onfocus event in Chrome's JavaScript add-on fails to trigger

A few months back, I encountered an issue where onFocus events added using JavaScript were not firing only in Chrome (my version Version 103.0.5060.114 (Official Build) (x86_64) OSX 12.4). Interestingly, they worked fine in iOS Chrome, other browsers, an ...

What are the best practices for sharing context in express and typescript?

Implementing a solution to expose a value to all request handlers using express and typescript is my goal. I am looking for a way to easily "inject" this value from a middleware or an alternative method that allows for simple mocking if needed. Here is th ...

Struggling with handling numbers and special symbols in the Letter Changes problem on Coderbyte

Hello I have been struggling to find a solution for my current issue. The problem lies within an exercise that requires changing only alphabetical characters, but test cases also include numbers and special characters which are being altered unintentionall ...

405 - Sorry, this method is not allowed for deletion

The issue at hand involves a Spring RESTful web service and a client. When attempting a DELETE request on the server, the following error is encountered: -> DELETE http://localhost:8080/employee/3/logout 405 (Method Not Allowed) Despite implementing th ...

Errors persist with Angular 2 iFrame despite attempts at sanitization

Attempting to add an iFrame within my Angular 2 application has been challenging due to the error message that keeps popping up. unsafe value used in a resource URL context The goal is to create a dynamic URL to be passed as a parameter into the iFrame ...

Conceal elements with a single click of a button

How can I use jQuery to hide all li elements with an aria-label containing the word COMPANY when the Search from documents button is clicked? Here is the HTML code: <ul class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content" id="ui-id-1" t ...

Switching views in AngularJS by using a controller to control the content displayed in the

My JavaScript web app utilizes AngularJS to simplify tasks, but I've encountered an issue. I'm trying to change views from an ng-controller using $location.path, but for some reason, the view isn't updating even though the path in the $loca ...

Error: Unexpected token : encountered in jQuery ajax call

When creating a web page that requests remote data (json), using jQuery.ajax works well within the same domain. However, if the request is made from a different domain (e.g. localhost), browsers block it and display: No 'Access-Control-Allow-Or ...

Having trouble with a 400 Bad Request error when sending a POST request from my Vue application to my Rails API

Currently delving into the world of Rails and Vue, I decided to take on a small project involving a basic Rails API and Vue app to practice making GET and POST requests from my Vue app to the Rails API. While GET requests are working smoothly, I'm enc ...