Validate PayPal button input

SDKLegacyLast updated: November 8th 2022, @ 10:41:15 am


Sometimes it is necessary to run validation when the PayPal buttons are clicked. For example, your page might contain a web form that must be valid before the transaction initiates.

For an optimal buyer experience, PayPal recommends completing the majority of this validation prior to rendering the buttons.

For validation that you cannot complete before rendering the buttons, follow this guide to run validation when clicking the PayPal buttons.

Synchronous validation

Whenever possible, PayPal recommends setting up synchronous validation for your page. This results in the best possible user experience because the buyer sees instant feedback and no popup window displays.

<p id="error" class="hidden">Please check the checkbox</p>
<label><input id="check" type="checkbox"> Check here to continue</label>

<script>
  paypal.Buttons({

    // onInit is called when the button first renders
    onInit: function(data, actions) {

      // Disable the buttons
      actions.disable();

      // Listen for changes to the checkbox
      document.querySelector('#check')
        .addEventListener('change', function(event) {

          // Enable or disable the button when it is checked or unchecked
          if (event.target.checked) {
            actions.enable();
          } else {
            actions.disable();
          }
        });
    },

    // onClick is called when the button is clicked
    onClick: function() {

      // Show a validation error if the checkbox is not checked
      if (!document.querySelector('#check').checked) {
        document.querySelector('#error').classList.remove('hidden');
      }
    }

  }).render('#paypal-button-container');
</script>

Asynchronous validation

Some validation must be done on the server-side or using an asynchronous channel. Learn how to run asynchronous validation when clicking the button.

Do not use asynchronous validation for any validation that can be done synchronously as it degrades the buyer's experience.

<p id="error" class="hidden">Please check your information to continue</p>

<script>
  paypal.Buttons({

    // onClick is called when the button is clicked
    onClick: function(data, actions) {

      // You must return a promise from onClick to do async validation
      return fetch('/my-api/validate', {
        method: 'post',
        headers: {
          'content-type': 'application/json'
        }
      }).then(function(res) {
        return res.json();
      }).then(function(data) {

        // If there is a validation error, reject, otherwise resolve
        if (data.validationError) {
          document.querySelector('#error').classList.remove('hidden');
          return actions.reject();
        } else {
          return actions.resolve();
        }
      });
    }

  }).render('#paypal-button-container');
</script>