Get rid of the :valid pseudo-class on input elements using JavaScript

My form has multiple sections that are manually validated using Bootstrap 4 validation, without actually submitting the form. The current code works well for this;

let eventCreationForm = $(".event-creation-form");
if (!eventCreationForm[0].checkValidity()) {
    eventCreationForm.find(":submit").click();
}

However, I only want to highlight the inputs that are invalid and not those that are valid in green. Instead of modifying the bootstrap styles, I thought about removing the :valid pseudo-class from the valid inputs. However, I haven't found any examples of this approach being used. Most solutions on platforms like SO involve changing styles through CSS.

I attempted something like this,

eventCreationForm.find(":valid").removeClass(":valid");
but it seems ineffective since ":valid" is not a real class.

The example snippet below throws a callstack error, but that's expected in this context.

$(document).ready(function(){
    var forms = document.getElementsByClassName('needs-validation');
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
        form.classList.add('was-validated');
      }, false);
    });
    
    $(".manual-submit").click(function(){
      let eventCreationForm = $(".event-creation-form");
      if (!eventCreationForm[0].checkValidity()) {
        eventCreationForm.find(":submit").click();
      }
    })
  })
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<form class="needs-validation event-creation-form" novalidate>
  <div class="form-row">
    <div class="col-md-4 mb-3">
      <label for="validationCustom01">First name</label>
      <input type="text" class="form-control" id="validationCustom01" placeholder="First name" value="Mark" required>
      <div class="valid-feedback">
        Looks good!
      </div>
    </div>
    <div class="col-md-4 mb-3">
      <label for="validationCustomUsername">Username</label>
      <div class="input-group">
        <div class="input-group-prepend">
          <span class="input-group-text" id="inputGroupPrepend">@</span>
        </div>
        <input type="text" class="form-control" id="validationCustomUsername" placeholder="Username" aria-describedby="inputGroupPrepend" required>
        <div class="invalid-feedback">
          Please choose a username.
        </div>
      </div>
    </div>
  </div>
  <button class="btn btn-primary manual-submit">Submit form</button>
</form>

Answer №1

It seems that the :valid pseudo-class cannot be removed based on what I currently know.

Nevertheless, the issue does not lie with those pseudo-classes. In Bootstrap 4, if you do not include the was-validated class in the form and manually add the is-invalid class where necessary, it will behave as requested in the question.

According to the Bootstrap 4 documentation:

If needed, use .is-invalid and .is-valid classes instead of the pseudo-classes for server side validation. No .was-validated parent class is required.

(Emphasis added.)

The reason why the :valid and :invalid pseudo-classes are being styled is due to the presence of the was-validated class on the parent element:

Bootstrap confines the styles for :invalid and :valid to the parent .was-validated class, usually assigned to the <form>. Without this, any mandatory field without a value appears as invalid when the page loads. This approach lets you decide when to activate them (typically after attempting to submit the form).

Answer №2

One clever way to switch between the pseudo-classes :valid and :invalid in JavaScript is by using the setCustomValidity() method.

According to the guidance provided in the Bootstrap 4 documentation (which also applies to Bootstrap 5):

You have the option to set custom error messages using the setCustomValidity function in JavaScript.

If you want to apply :invalid styling and remove :valid, you can do so like this:

var error = "An invalid input message.";
this.setCustomValidity(error);

On the other hand, if you wish to add :valid styling and remove :invalid, you can achieve this with the following code:

this.setCustomValidity("");

In addition to these methods, you can also manipulate the content of certain elements to add, remove, or modify error messages as needed.

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

Is it possible to display a website page that includes X-Frame-Options: deny in its header response using ReactJS?

I am attempting to display a webpage with the X-Frame-Options: deny setting in a React application. Since I cannot utilize the <iframe> element, I am exploring alternative methods to render the page. Unfortunately, modifying the server side configu ...

Error message: "Error occurred due to the undefined object in React UseEffect and

In my ClientData.js file, I am utilizing the useEffect hook to initiate an API call, which is functioning as intended. Subsequently, I am using useState to assign the response data from the API to a variable, which is also working properly. The retrieved ...

The drop down menu is not activating upon selection change

When it comes to selecting the duration of stay, I am attempting to display a dropdown menu for the number of guests using jQuery. <form class="form-inline" method="get" action="#" th:action="#" id="search"> <div class="input-group input-gr ...

Running a Mongoimport command within a JavaScript/Node.js script

Is there a node.js/javascript library available that allows for the use of mongoimport within code? From what I understand, mongoimport is similar to an .exe file that needs to be executed before being able to utilize its text input environment. Is it fe ...

Element vanishing post JSON parsing

I have encountered an intriguing issue: I have developed an HTML/JS project that extracts information using XMLHttpRequest from the Scratch website. The main objective is to allow users to input their username and view their profile description on Scratc ...

What is the method for ensuring a variable returns a number and not a function?

I've encountered a perplexing issue that I can't seem to solve. What could be causing the code below to output a function instead of a number? let second = function(){ return 100 }; console.log(second); ...

Navigation bar disappears when the page is scrolled to the top

Having an issue with the navbar functionality on my website. It is working properly in Firefox, but not in Chrome and Safari. When scrolling back up to the very top of the page, the navbar hides due to a minor bounce effect which triggers the hide action. ...

Connect ngOptions to an array beyond the current scope

Can the ngOptions be bound to a value that is not within the $scope? I have enums that will be generated as JavaScript code. These enums are not currently part of "the angular domain", but I want to bind an ngOptions to one of the arrays without manually ...

What is the best way to merge two arrays, preserving all keys and values without any overwriting?

Trying to explain this might be a bit tricky, but hopefully I am able to convey my message clearly. Let's say you have an array structured like this: mainArray: [ { name: '', age: null, gender: null, hobbies: [ ...

Choosing the ID and class name through jQuery among numerous classes

I am looking to create a Modal Pop Up Box using CSS and JS, but I need help getting the id (mymodal , mybtn) and the Class (close) from the span Element in JavaScript. Please refer to the attached link for an explanation of the code. div class="head ...

Disabling Babel in Nuxt.js: A Step-by-Step Guide

I've come to the decision to eliminate Babel transpilation from my projects, as I no longer see the need to accommodate pre-ES6 era browsers. However, my search efforts have yielded no results on how to go about this. My Nuxt project is currently fill ...

completion of bootstrap content

When arranging content using Bootstrap, I noticed that when the image is on the left, it appears to adapt properly. However, if I place the image on the right, the layout changes from what was intended. How can I fix this issue? <div class="about&q ...

Enhancing FileUpload functionality in ASP.NET with jQuery function prior to postback

My webpage is built with .aspx and contains the following code: .. <form id="frm" runat="server"> <asp:FileUpload runat="server" id="fileupload" onchange="browsed()" /> <asp:Button runat="server" OnClick="Upload_Click" id="uploadb ...

Creating an array of logos in ReactJS with the help of TailwindCSS

After seeing multiple implementations of this feature, I find myself struggling to search for a solution. I can only access the HTML and CSS through inspecting elements, wondering if others are facing the same issue as me. Typically, we aim to implement t ...

Logging in using Selenium WebDriver in Java

I'm just starting out with selenium webdriver and I need to automate a webpage for my project. Right now, I'm working on the login page but I'm having trouble with the login button. I'm not sure which locator to use for it. The login bu ...

Looking to eliminate the top border of the first cell

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="680a07071c1b1c1a4f5f5d465a465b">[email protected]</a>/dist/css/bootstrap.min.css"/> <br/> < ...

Enclose the quotes within an array in JSON format

I've been attempting to construct a JSON array, but I'm encountering some issues: var sample = '{"sections":[{"id":"example1", "title":"Data Analysis", "command":"openSection("analysis")"}]}'; I've identified the problem with the ...

Can anyone provide guidance on how to make slideToggle move upwards with jQuery?

<div class="row"> <div class="col-lg-2" ></div> <div class="head" style="background-color: #1c94c4; text-align: center; cursor: pointer;"> Connect</div> <div class="chat" style="display: none;width:a ...

Zod: Generate a basic item using default settings

I have a strong belief that this concept exists, however, my research has not yielded any results. Let's consider a scenario where I have a zod Schema structured like this: const Person = zod.object({ name: z.string().default(''), ag ...

What is the best way to refresh a page during an ajax call while also resetting all form fields?

Each time an ajax request is made, the page should refresh without clearing all form fields upon loading Custom Form <form method='post'> <input type='text' placeholder='product'/> <input type='number&a ...