Building a secure form validation system with Bootstrap 4 and integrating Stripe checkout functionality

Can someone help me figure out how to display the Stripe payment popup only when the Bootstrap 4 form is valid?

✔ The Bootstrap code is functioning correctly when the form is invalid.
𐄂 Issue: I attempted to use an 'if else' statement to make the Stripe popup appear when the form is valid, but it's not working :(

(function() {
  'use strict';
  window.addEventListener('load', function() {
    // Grab all the forms we want to apply customized Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation');
    // Iterate over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form[0].checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        } else {
          var handler = StripeCheckout.configure({
            key: 'pk_test_zef7efzhke73gefezzzhgu3',
            image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
            locale: 'auto',
            token: function(token) {
              // You can access the token ID with `token.id`.
              // Send the token ID to your server-side code for processing.
            }
          });
          // Initiate Checkout with additional options:
          handler.open({
            name: 'Test',
            description: '2 widgets',
            currency: 'eur',
            amount: 2000
          });

          // Close Checkout on page navigation:
          window.addEventListener('popstate', function() {
            handler.close();
          });
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();

Answer №1

The demo code provided for this bootstrap component only prevents form submission if validation fails. However, in your scenario, you need to prevent form submission at all times to avoid redirection to another page or reloading the current page once validation is successful. Instead, you want to open the Checkout modal.

An easy solution is to rearrange the following lines before the if statement:

event.preventDefault();
event.stopPropagation();

Additionally, it is advisable to move the StripeCheckout.configure(...) outside the validation logic to ensure Checkout is instantiated only once when the page loads.

Here is a complete snippet I used to address this issue. Keep in mind that you may need to add code in the token: function(token) {...} callback to send the token to your backend after completion:

<script>
// Sample JavaScript to disable form submissions with invalid fields
(function() {
  'use strict';
  var handler = StripeCheckout.configure({
      key: 'pk_test_g6do5S237ekq10r65BnxO6S0',
      image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
      locale: 'auto',
      token: function(token) {
          // Access the token ID with `token.id`.
          // Send the token ID to your server-side code.
      }
  });
  window.addEventListener('load', function() {
    // Select all forms with custom Bootstrap validation styles
    var forms = document.getElementsByClassName('needs-validation');
    // Prevent form submission
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        event.preventDefault();
        event.stopPropagation();
        if (form.checkValidity() === false) {
          // Custom behavior for Validation failure
        } else {
          // Open Checkout with additional options:
          handler.open({
              name: 'Test',
              description: '2 widgets',
              currency: 'eur',
              amount: 2000
          });
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();
</script>

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

Leverage the `dispatch` hook within a useEffect function

When it comes to triggering an action upon the React component unmounting, I faced a challenge due to hooks not allowing the use of componentWillUnmount. In order to address this, I turned to the useEffect hook: const dispatch = useDispatch(); useEffect(( ...

One helpful tip for adjusting the size of a UI chip on the fly

I am attempting to adjust the size of a UI chip dynamically based on the font size of its parent elements using the em unit in CSS. My objective is to achieve something like this: style={{size:'1em'}} The issue I'm encountering: The chip e ...

Maximizing the potential of mouse positioning in Angular

I am working with an Angular form that has a textarea <textarea class="form-control" id="message" formControlName="message" (fo ...

Error message received when calling a function within a Vue watcher states "function is not defined"

My goal is to trigger a function in a Vue component when a prop changes using a watcher: props: [ 'mediaUrl' ], watch: { mediaUrl: function() { this.attemptToLoadImage(); } }, medthods: { attemptToLoadImage: function() { console ...

"None of the AJAX callbacks are triggered, neither success nor error functions are being executed

document.getElementById('myform').addEventListener('submit', function (e) { // avoid the default action of the submit e.preventDefault(); $(function () { var artist = document.getElementById("artist"); var rows = document.getEl ...

Is it feasible to create that specific character using Google Charts?

Quick question here. Can a Char be generated in Google Charts? Also, do you have any advice on how to do this? Chart1 The blank space under the chart is crucial. ...

Enhance your ReactJS application by integrating Bootstrap 4 for a sleek

Recently, I installed bootstrap 4 using yarn add, but now I'm facing issues with using components that rely on JavaScript as they require jQuery. Can anyone guide me on where to find the webpack file for adding files related to jQuery and Proper? My p ...

The edit functionality in jqGrid does not function properly if custom search parameters are designated

Using the Guriddo jqGrid JS version 5.2.0 implemented here: @license Guriddo jqGrid JS - v5.2.0 - 2016-11-27 Copyright(c) 2008, Tony Tomov, [email protected] The code block below showcases an entire self-contained implementation of jqGrid. It inclu ...

Utilizing tag keys for inserting text and adjusting text sizes within a Web application

Creating an online editing interface for coursework where keyboard events are used. The goal is to have the tab key insert text, while also reducing the size of the text on that line. However, upon using getElementById, an error message pops up stating: ...

Example of Utilizing Google Places API

The Issue I've been struggling to make this google maps API example function correctly. Even after directly copying the code from Google's website, the example fails to display properly. For instance, the map doesn't show up, the search bar ...

"Update data on a webpage using Javascript without the need to refresh the

I encountered a problem with my code for posting messages in the "chatbox". When I include return false; at the end of the function, the data is not submitted. However, if I remove it, the data submits successfully. JavaScript Code function dopost() { ...

What is the best method for implementing numeric input in Vue.js?

I have experience developing web apps using Nuxt.js. I am currently trying to implement validation that excludes negative values and decimal points in all input tags (around 20-30) within the same Vue component. My approach involves injecting validation ru ...

What is the best way to automatically create a PDF file that includes interactive JavaScript charts?

My goal is to create a word document or PDF containing charts from various JavaScript chart libraries. I've successfully implemented these libraries on websites, but now I want to include them in my documents as well. My initial attempt involved usin ...

Executing an AJAX request with a specific state in Node.js

Instead of rendering add.jade directly, I have chosen to enhance the user experience by making an AJAX call to the endpoint. This allows me to maintain the URL as localhost:3000/books, rather than localhost:3000/books/add which lacks navigation state for ...

Validating Angular UI without requiring an input field (validating an expression)

Currently, I am utilizing ui-validate utilities available at https://github.com/angular-ui/ui-validate The issue I am facing involves validating an expression on a form without an input field. To illustrate, consider the following object: $scope.item = ...

Exploring the process of retrieving data from localStorage in Next.js 13

Having recently delved into the realm of Next JS, I've encountered a hurdle when it comes to creating middleware within Next. My aim is to retrieve data from local storage, but I keep hitting roadblocks. middleware.ts import { key, timeEncryptKey, to ...

Create a JavaScript function that accepts an argument and can be called both with and

Does anyone know how this code works? function animate(t) { sun.rotation.y = t/1000; renderer.clear(); camera.lookAt(sun.position); renderer.render(scene, camera); window.requestAnimationFrame(animate, renderer.domElement); ...

What's the reason why Angular stops flickering with the use of "/" in href?

Recently, I've come across a peculiar issue in one of my web applications while using Angular's routeProvider as a template engine. The app functions properly, but the behavior seems inexplicable to me. The problem arises during page transitions ...

Tips for managing numerous HTTP requests in Angular 6

I have a method that is trying to chain together 3 requests like this: showProfileDetails() { this.getUserInfo(this.currentUser.id).pipe( mergeMap(e => this.getAccounts(this.currentUser.id) ), mergeMap(e => this.getPayments ...

Using jQuery and regex to only allow alphanumeric characters, excluding symbols and spaces

Seeking advice, I am using a jquery function called alphanumers var alphanumers = /^[a-zA-Z0-9- ]*$/; which currently does not allow all symbols. However, I now wish to disallow the space character as well. Any suggestions? ...