How do I activate validation within bootstrap4 using bootstrap-validate?

I am working with a validation form in Bootstrap4 that displays an error message when less than 5 characters are entered.

If I enter 5 or more characters, I want to show a green check-mark and border around that specific input field.

<div class="container">
    <form action="" class="needs-validation" novalidate>
         <div class="form-group">
              <label for="username">username:</label>
              <input type="text" class="form-control" id="name"    placeholder="username" required> 
         </div>
        <input type="submit" class="btn btn-primary" value="submit" >
     </form>
    </div>


<script src="./dist/bootstrap-validate.js"></script>
 <script>
   bootstrapValidate('#name', 'min:5:Enter at least 5 charecters');
 </script>

</body>
 </html>

https://i.sstatic.net/zc1Bo.png

https://i.sstatic.net/yVMj1.png

https://github.com/NinoosMoshi/form-validation.git

Answer №1

To ensure your code functions correctly, you will need to make a few adjustments:

  • Verify that the condition is correct and adjust classes using bootstrapValidate accordingly
  • Import an icon library (such as font awesome v5)
  • Place the check mark icon in the classes you are adding/removing

UPDATE: Considering the query about multiple fields in the form

The following code snippet might assist:

$(document).ready(function() {
  bootstrapValidate('#usr', 'min:5:Enter at least 5 characters!', function(isValid) {
    if (isValid) {
      $("#formHolder").addClass('validClass');
      $("#formHolder").removeClass('invalidClass');
    } else {
      $("#formHolder").addClass('invalidClass');
      $("#formHolder").removeClass('validClass');
    }
  });
  bootstrapValidate('#lastName', 'min:7:Enter at least 7 characters!', function(isValid) {
    if (isValid) {
      $("#formHolder2").addClass('validClass');
      $("#formHolder2").removeClass('invalidClass');
    } else {
      $("#formHolder2").addClass('invalidClass');
      $("#formHolder2").removeClass('validClass');
    }
  });
});
.validClass>input {
  border: 2px solid green;
}

.validClass .form-control:focus {
  border-color: green;
  box-shadow: 0 0 0 0.2rem rgba(33, 93, 30, 0.56)
}

.invalidClass>input,
.invalidClass .form-control:focus {
  border: 2px solid red;
}

.inputWrapper {
  display: inline-block;
  position: relative
}

.validClass:after {
  font-family: "Font Awesome 5 Free";
  content: "\f00c";
  visibility: visible;
  font-weight: 900;
  color: green;
  position: absolute;
  right: 6px;
  top: 55%;
}

.invalid-feedback {
  position: absolute;
  display: inline-block;
  bottom: -100px;
  left: 0px;
}

.submitBtn {
  margin-top: 20px;
}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdn.rawgit.com/PascaleBeier/bootstrap-validate/v2.2.0/dist/bootstrap-validate.js"></script>
<link rel='stylesheet' href='https://use.fontawesome.com/releases/v5.7.0/css/all.css' integrity='sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ' crossorigin='anonymous'>

<div class="container mt-3">
  <form>
    <div class="form-group">
      <div class='inputWrapper invalidClass' id='formHolder'>
        <label for="usr">Name:</label>
        <input type="text" class="form-control " id="usr">
      </div>
      <br/>
      <div class='inputWrapper invalidClass' id='formHolder2'>
        <label for="lastName">last Name:</label>
        <input type="text" class="form-control " id="lastName">
      </div>
    </div>
    <button type="submit" class="btn btn-primary submitBtn">Submit</button>
  </form>
</div>

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

I'm receiving a Reference Error stating that 'next()' is not defined, despite the fact that I have defined it in my JavaScript code. What could be causing this issue?

I have a javascript function called next() to process information and then call the function from HTML. However, my Firefox console is showing a ReferenceError: 'next' is not defined. I am aware that there is an error in my code, but I cannot pin ...

How to use Jquery to elevate table rows to the top

Initially, I saved all my tr elements using a function and then targeted specific trs by clicking on them: // tr = all my stored trs tr.find("input[value='Selecteren']").click(); // This .click() function changes the input value to "Aanvragen" ...

Enhance the dropdown menu by incorporating a caret icon

Click here for the image, I am trying to incorporate the Bootstrap caret class into my select dropdown menu. .select_menu{ font-size: 12px; outline: none; border: thin #ddd solid; -webkit-appearance: none; -moz-appearance: none; appearance: ...

The most effective method for positioning a child element to the left and top using Flexbox grid

I am currently working on visualizing queues and processes within a system. Each process is associated with a specific queue from which it retrieves data. I aim to create a layout similar to the following: https://i.stack.imgur.com/BXyts.png However, I a ...

Tips for testing Sequelize with Jasmine

In my database/index.ts file, I set up a Sequelize database using the code below: import { Sequelize } from 'sequelize'; const { DATABASE_DIALECT, DATABASE_HOST, DATABASE_PORT, DATABASE_USER_NAME, DATABASE_USER_PASSWORD, DATABASE_NAM ...

The background image is failing to display, although other styles for the class or element are visible

Why won't the background image display, even though I have verified that the image path is correct and changing other properties like color or background color works just fine? Here is my CSS code snippet: .container { background-imag ...

organizing arrays with the structure name:url

I have a list of string URLs like "http://dom/image1.jpg","http://dom/image2.jpg" that I obtained from an API which returns only the links. However, the plugin I am using requires the array to be in a specific format: {image:"http://dom/image1.jpg"},{imag ...

Verify if Javascript is enabled

Can I determine if the browser supports or has Javascript enabled? If not supported, my goal is to direct the user to a more user-friendly error page. My current tech stack includes jQuery and PHP Zend Framework. ...

Can images be shown on a different PHP page?

My current project involves annotating images of vials with defects. I have organized these images into folders based on their batch numbers. Each folder is named according to its respective batch number. Once all the images are uploaded, I need to retriev ...

Pause the loading of information for a brief 2-second interval using jQuery's ajax feature

I want to enhance the user experience by loading search results using jQuery ajax within a div container. To achieve this, I am looking to introduce a 2-second delay before displaying the results or show them only after the user has entered at least three ...

Identifying added elements that respond to link hover effects

I've been working on a project where I'm trying to replace the default browser cursor with an SVG one using jQuery. Everything seems to be working smoothly, except for changing the cursor when it hovers over links - nothing I've tried so far ...

Use AppScript to exclude the first row (which contains the column names) when filtering a table

Considering the limitations of Google Sheets with the ImportRange function, I decided to develop an AppScript as a replacement. Although I am new to JavaScript, here is what I have so far: function My_ImportRange() { var clearContent = SpreadsheetApp.ge ...

Using the $inc operator in mongoose to avoid decrementing a value below zero

My code successfully deducts credit from a user using $inc in Mongoose, but the concern is that the value can become negative, which is not ideal. Is there any way to prevent this? module.exports.deduct_credit = function(subscriber_email,callback){ Us ...

ways to change date format in a React.js application using JavaScript

<b>Choose Date and Time</b><br/> <DateTimeField onChange={this.clockevent} format={"x"}/> clockevent=(newDate)=>{ var dateVal ="/Date("+newDate+")/"; var date = new Date(parseFloat(dateVal.substr(6))); console.log( ...

Is it possible to align the modal based on the mouse's position or a specific element?

Recently, I completed a React project that utilizes an API to search for movie titles. The project returns a list of movies corresponding to the user's search query. Everything seems to be working fine up to this point. However, I encountered an issu ...

JSON parsing problem in web browsers

I've been working on an application using Asp.net MVC. When I submit the form using jQuery: var Data = $("#frmForgotPassword").serialize(); $.post("<%= Url.Action("ForgotPassword","Account") %>/", Data, function(retdata, textStatus) { if ( ...

Extracting the contents of a div element from the HTML data retrieved through AJAX

I am no expert in jQuery and Ajax, so I apologize if this question is bothersome. Despite searching online, I haven't been able to find a simple answer. I'm particularly curious about the HTML data that is returned from an Ajax call, which conta ...

Implementing cross-app module injection in Node.js

I have two node apps/services that are currently running together: 1. the main app 2. the second app The main app is responsible for displaying all the data from different apps in the end. Currently, I have taken some code from the second app and integra ...

"Utilize JavaScript to extract data from JSON and dynamically generate a

I'm currently facing an issue with reading JSON data and populating it in my HTML table. The function to load the JSON data is not working as expected, although the data typing function is functioning properly. I have shared my complete HTML code alo ...

How nicEdit reacts upon being returned from a jQuery AJAX call

Utilizing nicEdit to enhance text editing capabilities in a textarea. Integrating nicEdit with Codeigniter MVC framework and jQuery to facilitate an AJAX request to generate a new textarea and applying nicEdit to it upon retrieval. The integration is succe ...