tay
tay

Reputation: 168

How can I disable the Stripe payment request button until a form is complete?

I have Stripe's payment request button set up on the same page as a form. The form has validation on it. I need to be able to disable the payment request button until the form has been completed but I haven't been able to find a way to do this.

Payment request button set up:

<script src="https://js.stripe.com/v3/"></script>
<div id="payment-request-button">
  <!-- A Stripe Element will be inserted here. -->
</div>
<script>
var stripe = Stripe('KEY');
var paymentRequest = stripe.paymentRequest({
  country: 'US',
  currency: 'usd',
  total: {
    label: 'Demo total',
    amount: 1000,
  },
  requestPayerName: true,
  requestPayerEmail: true,
});

var elements = stripe.elements();
var prButton = elements.create('paymentRequestButton', {
  paymentRequest: paymentRequest,
});

// Check the availability of the Payment Request API first.
paymentRequest.canMakePayment().then(function(result) {
  if (result) {
     prButton.mount('#payment-request-button');
   } else {
     document.getElementById('payment-request-button').style.display = 
 'none';
   }
 });

 paymentRequest.on('token', function(ev) {
   // Send the token to your server to charge it!
   fetch('/charges', {
     method: 'POST',
     body: JSON.stringify({token: ev.token.id}),
     headers: {'content-type': 'application/json'},
  })
  .then(function(response) {
    if (response.ok) {
      // Report to the browser that the payment was successful, prompting
      // it to close the browser payment interface.
      ev.complete('success');
    } else {
      // Report to the browser that the payment failed, prompting it to
      // re-show the payment interface, or show an error message and close
      // the payment interface.
      ev.complete('fail');
    }
  });
});
</script>

Upvotes: 10

Views: 5380

Answers (1)

fumoboy007
fumoboy007

Reputation: 5543

You can perform form validation in an event handler for the click event of the payment request button.

Example

prButton.on('click', function(event) {
  if (!myForm.reportValidity()) {
    event.preventDefault();
    return;
  }
});

Documentation

element.on('click', handler)

Triggered when the Element is clicked. This event is only emitted from a paymentRequestButton Element.

handler

When called it will be passed an event object with the following properties:

preventDefault

Calling this function synchronously prevents the browser's payment interface from being shown. This can be used to validate the form before the payment interface is shown.

Upvotes: 11

Related Questions