Make sure to confirm the input length and utilize bootstrap validation for error checking

I have a rather straightforward question. I am currently utilizing Bootstrap 4.6 and am looking to implement form validation for my input field.

The requirement is to validate whether the input has a length of 5 characters or less, in which case it should display as "not fulfilled" in red. If the input is equal to or longer than 5 characters, it should display as fulfilled, indicated by green text.

Red: https://i.sstatic.net/Q99cs.png

Green: https://i.sstatic.net/u8AuI.png

I would like to use the Bootstrap 4.6 validation feature - you can find more information about this component here: https://getbootstrap.com/docs/4.6/components/forms/#validation

Thank you in advance for your assistance!

Below is the code snippet:

<form class="was-validated">
  <div class="mb-3">
    <label for="validationTextarea">Textarea</label>
    <input class="form-control" id="validationTextarea" placeholder="Required example textarea" onkeyup="checkInput()" required></input>
  </div>
</form>
function checkInput() {
  var input = document.getElementById("validationTextarea").value;

  if(input.length < 5) {
    //display in red
  } else if (input.length >= 5) {
    //display in green
  }
}

Answer №1

Should you desire a customized validation approach, follow these steps:

1) Start by removing the was-validated class from the form element to allow for custom validation:

  <form class="m-3"> 
    <div class="mb-3">
      <label for="validationTextarea">Textarea</label>
      <input class="form-control is-invalid" id="validationTextarea" placeholder="Required example textarea" onkeyup="checkInput()" required></input>
    </div>
  </form>

2) Proceed with implementing the logic: Add the is-invalid class if the length of values is less than 5, otherwise add the is-valid class.

const input = document.querySelector( "#validationTextarea" );

function checkInput() {
    var value = document.getElementById( "validationTextarea" ).value;

    if ( value.length < 5 ) {
        input.classList.remove( "is-valid" );
        input.classList.add( "is-invalid" );
    } else {
        input.classList.add( "is-valid" );
        input.classList.remove( "is-invalid" );
    }
}

const input = document.querySelector("#validationTextarea");

function checkInput() {
  var value = document.getElementById("validationTextarea").value;

  if (value.length < 5) {
    input.classList.remove("is-valid");
    input.classList.add("is-invalid");
  } else {
    input.classList.add("is-valid");
    input.classList.remove("is-invalid");
  }
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e2c21213a3d3a3c2f3e0e7a6078607e">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>


<form class="m-3">
  <div class="mb-3">
    <label for="validationTextarea">Textarea</label>
    <input class="form-control is-invalid" id="validationTextarea" placeholder="Required example textarea" onkeyup="checkInput()" required></input>
  </div>
</form>

Answer №2

When working with React, I encountered a situation where input.classList.remove/add was not functioning as expected. To resolve this issue, I decided to utilize event.target instead.

function verifyInput(event) {
const content = document.getElementById("validationTextarea").value;

if (content.length < 10 || content.length > 140) {
    event.target.classList.add("is-invalid");
} else {
    event.target.classList.remove("is-invalid");
    event.target.classList.add("is-valid");
}

}

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

Get an Object Array and assign it to a state Array variable after filtering

Here is a JSON Input that I will be filtering by orderId and then setting to a state variable. [{"orderId":3,"userId":3,"firstName":"Amal","lastName":"kankanige","contactNo":"011-3456787","status":"pending","deliveryAddress":"No:24/c,Anders Road,Wijerama, ...

Expanding Gridview Width within a Container in ASP.Net: A Step-by-Step Guide

https://i.stack.imgur.com/ZaJE7.jpg After viewing the image above, I am facing a challenge with stretching and fixing a gridview to contain the entire div where it is placed. The issue arises when the gridview adjusts automatically based on the content&ap ...

How can I replay an HTML audio element?

I created an HTML5 page with an audio element for playing music in mp3 format. However, when the music plays to the end, it stops and I'm using JavaScript to control the audio element. Even so, I can't seem to replay it, only stop it. Is there a ...

Is there a way to share the Username and Password without the need to manually input it?

My goal is to develop a C++ application for my classmates at school. Currently, they are required to visit our school's website and navigate to the login page. Once there, they enter their username and password, log in, and proceed to find their spec ...

Retrieve the request body within the validation function of express-validator version 4

Recently, I began using express.js along with express-validator to validate input data. However, I have encountered a problem when trying to access the request body in the new check API introduced in version 4.0.0. In previous versions, it was simple to a ...

Modify the data format within the objects in the array

Here is an array of objects that I have: Object {Results:Array[2]} Results:Array[2] [0-1] 0:Object id=1 name: "Rick" Value: "34343" 1:Object id=2 name:'dav ...

Tips for safely executing an SQL query with electron.js

I have a new project where I need to interact with an SQL database on the local network, but it's not located on the same system I'm working on (not SQLExpress). So far, I've figured out how to collect user input on a webpage and send that ...

Modify an element upon clicking the mouse on an image

I am looking to dynamically change the paragraph element with className="details" to an editable input field when a user clicks on the image with className="edit-icon" within the same grid container. How can I achieve this functionality ...

Troubleshooting error: Unable to access property 'post' in Angular Service when using $http

As I delve into learning Angular, my approach involves shifting all the business logic to services. However, I encountered an error while attempting a post request within a service: Cannot read property 'post' of undefined Provided below is a ...

Enhancing Django's login form validation with AJAX

I'm trying to implement an AJAX login feature in Django. The goal is to check if the user has provided the correct username and password. Take a look at my current code setup: urls.py urlpatterns = [ url(r'^$', views.home_view, name=&a ...

What is the best way to retrieve the latest date from an array of objects?

I had an array of objects where each object contained startDate, endDate, ownerID, and ownerType. To get the documents, I used the following statement: var yesterdayDate = new Date(); yesterdayDate.setDate(yesterdayDate.getDate() - 1); var next30daysDate ...

Sending data from an external input field to a form using AngularJS programmatically with element name

I am facing a challenge where I need to include an Input element in a Form, even though the Input is located outside of the form. While I have managed to add the input using form.$addControl(outerInput), it is not producing the desired outcome as shown in ...

What is the best method to save changes made in a webdatagrid to a session?

My goal is to set the datasource of a grid to a session variable, bind it, and then add a row or rows to the dataset and save the changes back to the session. However, I am encountering an issue after trying to commit the changes, resulting in an AJAX sync ...

Is it a bad idea to set directive scope to false, considering the limitations on broadcasting in an isolated scope?

There is a unique situation I am trying to tackle where I need to use $broadcast within a directive's linking function that has an isolated scope. Unfortunately, broadcasting from inside an isolated scope becomes challenging as the directive scope doe ...

Is dividing a website into two parts acceptable?

In the process of creating a social network, one major concern is making sure that the content is easily readable by Google while also providing users with a seamless and engaging experience through Ajax support. However, it's well-known that Ajax and ...

the `req.body` method fetches an object with a property named `json

Having an issue with accessing data from req.body in my form created with JS { 'object Object': '' } //when using JSON.stringify: { '{"A":"a","B":"b","C":"c"}': &apo ...

Is it possible to update the event parameters with every click?

Is there a way to dynamically add a Select box for selecting a condition each time the "add" button is clicked? For example, when the add button is clicked, I would like the following elements to be continuously added: https://i.stack.imgur.com/6bad2.png ...

Display a loading indicator or progress bar when creating an Excel file using PHPExcel

I am currently using PHPExcel to create excel files. However, some of the files are quite large and it takes a significant amount of time to generate them. During the file generation process, I would like to display a popup with a progress bar or a waitin ...

What is the process of adding files to my Svelte / Sapper server build using __sapper__?

Currently, I am working on integrating a server middleware called Parse into my sapper server configuration located in sapper-project/src/server.js. express().use('/api', const api = new ParseServer({ databaseURI: 'mongodb://localhost:27 ...

Using regular expressions in JavaScript, how can one extract the content along with the HTML tags from within the tags?

Below is the text to be analyzed: how much production in batu The text is displayed with HTML tags where each word is wrapped in a span with a specific style or class. For example: '<span style="">how &nbsp;</span><span style ...