Using Bootstrap 4 beta for Form Validation

I'm struggling to grasp the concept of building validation forms. The bootstrap documentation includes a JS code snippet (referred to as starter code) like the one below:

<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
  'use strict';

  window.addEventListener('load', function() {
    var form = document.getElementById('needs-validation');
    form.addEventListener('submit', function(event) {
      if (form.checkValidity() === false) {
        event.preventDefault();
        event.stopPropagation();
      }
      form.classList.add('was-validated');
    }, false);
  }, false);
})();
</script>

While this code works well, I am now wondering how I could implement password checking, for instance. Bootstrap uses CSS classes :valid and :invalid which trigger when a field is empty. But what if I want them to run based on specific conditions, such as a password being less than 8 characters long?

<form id="needs-validation" novalidate>
    <div class="form-row">
        <div class="form-group col-md-6">
            <label for="inputPassword1">Password</label>
            <input type="password" class="form-control" name="inputPassword1" id="pass1" placeholder="password" required>
        <div class="invalid-feedback">
            Please provide a valid password.
        </div>
    </div>
</form>

Answer №1

You have the option to utilize the pattern attribute. According to MDN:

pattern This is a regular expression that ensures the value of the control meets specific criteria. The entire value must match the pattern, not just part of it. If the type attribute is text, search, tel, url, email, or password, this attribute is applicable; otherwise, it is ignored. The syntax follows the JavaScript RegExp algorithm, with the 'u' parameter indicating that the pattern should be treated as a sequence of unicode code points. There are no forward slashes around the pattern.

For instance, the example below will validate that the password contains at least 8 characters with a mix of upper and lower case letters, and numbers:

<form id="needs-validation" novalidate>
    <div class="form-row">
        <div class="form-group col-md-6">
            <label for="inputPassword1">Password</label>
            <input type="password" class="form-control" name="inputPassword1" id="pass1" placeholder="password" 
                   pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$"
                   required>
        <div class="invalid-feedback">
            Passwords must be a minimum of 8 characters including at least one uppercase letter, one lowercase letter, and one number.
        </div>
    </div>
</form>

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

Trouble with CSS Vertical Alignment: Solutions to Fix it

Link to a JSFiddle for reference: http://jsfiddle.net/STmwz/4/ Initially, there is only the top div displayed. Upon clicking the edit button, the JavaScript code replaces the top div with the bottom div. However, during this transition, there is a slight ...

When clicked, you will be redirected to the details page

Currently, I am developing a React JS application that showcases a list of companies fetched from a Node.js/Express server in a table format. When clicking on each row, it triggers a modal to display some details about the company. The modal consists of t ...

A PHP tag containing a div element

As someone who is new to web development, I have a question that may seem silly to some. I am familiar with adding div tags inside php tags, but I am unsure if it's possible to add onclick functions or any other type of function to these div tags. He ...

Discrepancy in sorting order of key-value objects in JavaScript

Check out my jsFiddle demonstration illustrating the issue: Example Here is the HTML structure: <select id="drop1" data-jsdrop-data="countries"></select> <select id="drop2" data-jsdrop-data="countries2"></select>​ Below is the ...

Is there a way to implement this code to filter every column in the grid?

I have been using this code in my grid view, but it only filters one column of the grid. Now I want to modify the code to filter multiple columns. I tried implementing a loop, but it seems like the code is not working correctly. Is there a way to adjust t ...

Using AngularJS to add a unique custom class directive to each item in an ng-repeat loop

Can anyone help me figure out why the width of a div isn't being set dynamically using AngularJS? <ul id="contents"> <li ng-repeat="content in contents"> <div class="content_right custom_width"> <div class="title"> ...

In JavaScript, when all values are false in an object, the object's value should be set to False

My task involves working with a JSON data object that contains multiple key-value pairs. I need to determine whether at least one value is false and set another variable to "false" accordingly. Here is the JSON data that I am handling: var objectVal = re ...

Facing challenges with parsing JSON files in an Angular 2+ application

Utilizing the Angular CLI, I have configured this project with the standard folder layout. My goal is to practice reading a JSON file from src/app/assets/items.json and then using it to display these items in the HTML. items.json: { "results": [ ...

Leveraging JSON in conjunction with AJAX and Python database operations

I am a beginner in Python and I am attempting to access the database through Python in order to retrieve results in a JSON array using AJAX. When I test it by returning a JSON list and triggering an alert in JavaScript, everything works fine. However, as ...

Converting an array of images into blob format and displaying it using PHP

I am attempting to convert an array of images into blob format and then send it to a PHP script for data processing. However, I am encountering an issue where the array of blobs is not being sent correctly, and I am unsure why this is happening. Here is my ...

AngularJS does not support the use of $(this) syntax

I have encountered an issue while developing a Chrome extension using AngularJS. I would like to add buttons to my popup page, and I want the ancestor node to disappear when a button is clicked. Here is the code snippet: in popup.html <div class="dea ...

Utilizing JavaScript to verify the presence of a div element within dynamically injected HTML code

While working on a website, I have implemented an embed function which involves calling a javascript from my server to inject HTML on another remote server. To ensure that these embeds also benefit from Google ranking, I have included a piece of HTML in t ...

Challenges with NPM testing

Are there any reported issues with npm on Ubuntu 18.04? Or are there known solutions to the 100:1 error? I am currently enrolled in a course and it's crucial for me to be able to execute code using npm test. Despite multiple attempts at deleting and ...

Text box size in user input not adapting on mobile devices

Website: Visit the Cutter Travel Calculator here I've encountered an issue with my user input text boxes on mobile. Despite setting their width using the formidable forms plugin, the size adjustment doesn't seem to apply when viewed on mobile de ...

How to Toggle Visibility of TH and TD Elements using Bootstrap 5

In my current setup, I have the following table: <table class="table table-sm table-borderless w-auto"> <thead> <tr> <th> <input type="checkbox" value="false" class="form ...

Incorporating dynamic images into Laravel using Angular

I am currently trying to dynamically input the src value of an image using Angular. Below is the code I have written : HTML : <div ng-app="myApp" ng-controller="MyCtrl"> <img src="{{asset('assets/img/'.'/'. @{{ item.name ...

I need to generate table rows using v-for and include a unique value in the 'id' attribute of each row

I am creating table rows dynamically in a view using Flask data. <tr id="<% file.id %>" v-for="file in fileList"> <td><img class="thumbnail_preview" src=""></td> <td><% file.filename %></td> <td> ...

Move the sprite to the center bottom of the orthographic camera

Looking for help positioning sprites at the bottom center of the orthographic camera. Here is the current setup - The object: function Obj() { const texture = useLoader(THREE.TextureLoader, loadedimg); const spriteRef = useRef(); return ( < ...

Issue with the functionality of Material-ui tooltip

I'm exploring the implementation of the material-ui tooltip feature and I am hoping to have it displayed at the top of the element. Despite specifying placement="top", the tooltip still does not appear as intended. You can view a demo of this issue b ...

Choosing text input after adding a dynamic HTML row can be done by identifying the specific characteristics

I am currently working on a CodeIgniter project where I have implemented a purchase form that allows users to search for spare parts items using autocomplete in an input text field. The initial search functionality is working fine, but when I try to add a ...