Personalized validation using Bootstrap V5

Currently, I am using the default Bootstrap V5 form validator and I am interested in finding a way to create a custom parameter that must be checked for the input to be considered valid. Specifically, I want users to input their license plate, which should consist of both letters and numbers. While I have managed to include this requirement, Bootstrap still considers the input valid even if it technically isn't, as it only checks for any input in the field. Is there a method for me to modify what Bootstrap defines as valid?

The default bootstrap validation function is shown below:

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

  // Fetch all the forms we want to apply custom Bootstrap validation styles to
  var forms = document.querySelectorAll('.needs-validation')

  // Loop over them and prevent submission
  Array.prototype.slice.call(forms)
    .forEach(function (form) {
      form.addEventListener('submit', function (event) {
        if (!form.checkValidity()) {
          event.preventDefault()
          event.stopPropagation()
        }

        form.classList.add('was-validated')
      }, false)
    })
})()

Answer №1

Having dedicated a significant portion of the afternoon to researching the same topic, it appears that there is a scarcity of information on implementing custom JS validation with the default Bootstrap validation. Based on my findings, I have identified two potential methods:

  1. Utilizing the pattern attribute on the element
  2. Incorporating your own JS validation within the checkValidity() expression

Pattern Attribute

When creating an input, it is possible to define a pattern attribute for the element.

Referencing the MDN pattern article:

<p>
 <label>Enter your phone number in the format (123) - 456 - 7890
  (<input name="tel1" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit area code" size=&qout;2"/>) -
   <input name="tel2" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit prefix" size=&qout;2"/> -
   <input name="tel3" type="tel" pattern="[0-9]{4}" placeholder="####" aria-label="4-digit number" size=&qout;3"/>
 </label>
</p>

This example illustrates the structure for a North American phone number, with each section denoted by a specified pattern attribute indicating expectations for 3-digits, 3-digits, and 4-digits respectively.

JS Validation

Upon invoking the checkValidity() method, integrate custom JS validation logic to reject form submission if necessary.

const myValidation = someValidation()

if (!myValidation || !form.checkValidity()) {
  event.preventDefault()
  event.stopPropagation()
}

For the someValidation() function, remember to adjust the validation classes accordingly:

// valid input
const foo = document.getElementById("foo")
foo.classList.remove("is-invalid")
foo.classList.add("is-valid")

// invalid input
const bar = document.getElementById("bar")
bar.classList.add("is-invalid")
bar.classList.remove("is-valid")

However, I am still exploring how to completely suppress the validation framework from displaying an input as valid (indicated by a checkmark on the right side) despite setting the appropriate classes. It seems related to having an empty pattern attribute, which signifies that the field cannot be left blank, and may require triggering the element's reportValidity() method: HTML Spec: reportValidity()

Conclusion

Evidently, leveraging the pattern attribute and RegEx is the recommended approach when working with this validation framework.

It is my hope that someone else can enhance this solution by offering a more effective strategy using pure JS techniques.

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

The art of combining arrays of objects while eliminating duplicates

I am in need of a solution to compare two object arrays, remove duplicates, and merge them into a single array. Although I am relatively new to javascript/Typescript, I have come across some blogs suggesting the use of Map, reduce, and filter methods for t ...

Deleting elements from the DOM in Vue.js

Utilizing Vue.js (version 3.x), I am dynamically rendering components. <div v-for="(i, index) in fields" > <my-component :id="index" ></my-component> <span class="delete-icon" @click="removeFi ...

Is there a way to retrieve the disabled drop-down field value after submitting the form?

I'm struggling with a dropdown field that becomes disabled once an item is selected. After submitting the form, the dropdown field loses its value and I'm left with an empty field. Any suggestions on how to keep a value in the dropdown after subm ...

How to include images in a PDF using jspdf without encountering issues with Adobe Reader?

For a project I'm working on, I've integrated jspdf to convert some charts into a PDF. The framework I'm using is angularjs 1.5.6, and the charts are created with chart.js. The HTML snippet for the charts looks like this: <div name="char ...

What could be the reason behind Next.js attempting to import a non-existent stylesheet?

Lately, I've come across an issue where Nextjs is attempting to import a non-existent stylesheet (refer to the images below). I'm looking for guidance on how to resolve this error. Hoping to find a solution here, thank you Web browser console W ...

Getting the user's name and country using `auth().createUserWithEmailAndPassword` is a simple process

Hey there fellow developers. I'm fairly new to react native and I'm trying to implement firebase authentication for a project. However, I'm stuck on how to include user name and country when using the standard auth().createUserWithEmailAndPa ...

Can Vuejs functions be triggered using a jQuery event trigger?

I am currently attempting to trigger a change event within a Vue component. Within the component template, there is a select element. When I try to use jQuery to trigger a change event on this element, the Vue component does not seem to detect it. Here i ...

Confirm the session validity before invoking the web service function from an ajax function triggered by clicking a button

I am experiencing a complex issue. On a page, users input data and then click on a button to save all the parameters into a JSON object. After saving locally, they click another button which triggers an ajax method that calls a web service method on the sa ...

Switch up the box-shadow color with ColorThief!

Is there a way to adjust this script to change the box-shadow color of #player1? <script type="text/javascript> $(window).ready(function(){ var sourceImage = document.getElementById("art"); var colorThief = new ColorThief(); var color = ...

The error thrown states: "TypeError: Unable to access the property 'getFieldDecorator' of undefined in a React component."

Encountering this error: > TypeError: Cannot read property 'getFieldDecorator' of undefined > _class.render src/containers/RegisterTenant/register.js:81 78 | this.setState({ 'selectedFiles': files }); 79 | } 80 | > ...

Issues with the Appearance of Flask Bootstrap Alerts and Close Button

Trying to implement Bootstrap alerts has been a bit tricky for me. I'm not sure what exactly I'm missing, but here's a simplified version of the code that highlights the issues... Python File from flask import Flask, render_template from fl ...

The Socket.io server running on Express is currently not reachable from any external devices

I currently have a basic application using socket.io and expressjs up and running. The application is hosting a simple HTML file, which I can successfully access through my browser. However, when attempting to access it from other devices on my network, th ...

bitcoinjs-lib for generating raw transactions in Node.js

var bitcoin = require('bitcoinjs-lib'); var rp = require('request-promise'); var data = Buffer.from('Hello World', 'utf8'); var testnet = bitcoin.networks.testnet; var privateKey = 'p2pkh'; var SourceAddre ...

jQuery - accessing a different class within the object

Let me explain the scenario: I have a website that will delve into 4 different subjects. Initially, I have 4 divs each representing the title of those subjects. For instance, <div><p> Physics </p></div> <div><p> Chem ...

Using jQuery to select the next table cell vertically

Is there a way to utilize jQuery to access the cell (td) directly below a given cell in a traditional grid-layout HTML table (where each cell spans only one row and column)? I understand that the code below will assign nextCell to the cell immediately to ...

Issue with ng-hide logic malfunctioning

I am currently developing an Ionic application and encountering some issues with the ng-hide directive. My goal is to display or hide a button based on whether the user has completed registration. The button in question: <button class="button button-c ...

Encountering a 500 Internal Server Error in Next.js immediately after invoking the useEffect Hook within a 404 Page

In my code, I utilize the useEffect hook to trigger a setTimeout function inside it in order to automatically redirect the user back to the home page after 3 seconds using the useRouter hook from Next.js and calling the push method on it. Everything works ...

Traverse through an array of pictures and add the data to a Bootstrap placeholder within HTML markup

In my quest to create a function that populates placeholders in my HTML with images from an array, I am encountering a problem. Instead of assigning each image index to its corresponding placeholder index, the entire array of images is being placed in ever ...

The art of linking JavaScript events

I'm encountering some challenges with linking events together. I've set up an eventListener on a variety of links that, when hovered over, trigger a drop-down menu to appear. Everything is functioning properly, but I also want triangular shapes ...

Using JavaScript to transfer the data ID from a button to a form

I am working on a project where I have a button that triggers a modal: <button type="button" class="btn btn-primary add-subscription" data-toggle="modal" data-workspace_id="{{ workspace.id }}" data-target="# ...