Subscribe to credit and debit card field events

DocsCurrent

Last updated: Oct 29th, 5:58am

Subscribe to events

You can subscribe to Advanced Credit and Debit Card payments events using an event listener. This allows you to update the UI of your form based on the state of the fields. These events include:

Event nameDescription
focusEmitted when a field gains focus.
blurEmitted when a field loses focus.
emptyEmitted when a field transitions from having data to being empty.
notEmptyEmitted when a field transitions from being empty to having data.
cardTypeChangeEmitted when the possible card type has changed. Only emitted from a change in the number field.
validityChangeEmitted when the validity of a field changes.
inputSubmitRequestEmitted when the customer requests submission of an input field, such as by pressing the Enter or Return key on their keyboard or mobile equivalent.

Set up an event listener using the advanced credit and debit card payments on() function. You can use the event object to get information about your fields and update your UI accordingly.

Here is an example of how you can use cardTypeChange to update your CVV label and placeholder:

    1paypal.HostedFields.render({ /* ... */ }).then(function (hostedFieldsInstance) {
    2 var cvvLabel = document.querySelector('label[for="cvv"]'); // The label for your CVV field
    3
    4 hostedFieldsInstance.on('cardTypeChange', function (event) {
    5 // This event triggers when a change in card type is detected.
    6 // It triggers only from the number field.
    7 var cvvText;
    8
    9 if (event.cards.length === 1) {
    10 cvvText = event.cards[0].code.name;
    11 } else {
    12 cvvText = 'CVV';
    13 }
    14
    15 cvvLabel.innerHTML = cvvText;
    16 hostedFieldsInstance.setAttribute({
    17 field: 'cvv',
    18 attribute: 'placeholder',
    19 value: cvvText
    20 });
    21 });
    22});

    To get the state of your form without using events, use the getState function. This example uses getState to confirm that all of the provided fields are valid before form submission.

      1var form = document.querySelector('#my-sample-form');
      2
      3paypal.HostedFields.render({ /* ... */ }).then(function (hostedFieldsInstance) {
      4 form.addEventListener('submit', function (event) {
      5 var state = hostedFieldsInstance.getState();
      6 var formValid = Object.keys(state.fields).every(function (key) {
      7 return state.fields[key].isValid;
      8 });
      9
      10 if (formValid) {
      11 // Submit Hosted Fields card data
      12 hostedFieldsInstance.submit();
      13 } else {
      14 // Let the customer know their fields are invalid
      15 }
      16 });
      17});

      Examples

      Here are examples of how you might use the event listeners.

      focus

      This event triggers when a field gains focus.

        1paypal.HostedFields.render({ /* ... */ }).then(function (hostedFieldsInstance) {
        2 hostedFieldsInstance.on('focus', function (event) {
        3 // Your actions on focus
        4 console.log(event.emittedBy, 'gained focus');
        5 });
        6});

        blur

        This event triggers when a field loses focus.

          1paypal.HostedFields.render({ /* ... */ }).then(function (hostedFieldsInstance) {
          2 hostedFieldsInstance.on('blur', function (event) {
          3 // Your actions on blur
          4 console.log(event.emittedBy, 'lost focus');
          5 });
          6});

          empty

          This event triggers when a field transitions from having data to being empty.

            1paypal.HostedFields.render({ /* ... */ }).then(function (hostedFieldsInstance) {
            2 hostedFieldsInstance.on('empty', function (event) {
            3 // Your actions on empty
            4 console.log(event.emittedBy, 'is now empty');
            5 });
            6});

            notEmpty

            This event triggers when a field transitions from being empty to having data.

              1paypal.HostedFields.render({ /* ... */ }).then(function (hostedFieldsInstance) {
              2 hostedFieldsInstance.on('notEmpty', function (event) {
              3 console.log(event.emittedBy, 'has data');
              4 });
              5});

              cardTypeChange

              This event triggers when activity within the number field has changed such that the possible card type has changed.

                1paypal.HostedFields.render({ /* ... */ }).then(function (hostedFieldsInstance) {
                2 hostedFieldsInstance.on('cardTypeChange', function (event) {
                3 if (event.cards.length === 1) {
                4 console.log(event.cards[0].type);
                5 } else {
                6 console.log('Type of card not yet known');
                7 }
                8 });
                9});

                validityChange

                This event triggers when the validity of a field has changed. Validity is represented in the event object as two booleans: isValid and isPotentiallyValid.

                  1paypal.HostedFields.render({ /* ... */ }).then(function (hostedFieldsInstance) {
                  2 hostedFieldsInstance.on('validityChange', function (event) {
                  3 var field = event.fields[event.emittedBy];
                  4
                  5 if (field.isValid) {
                  6 console.log(event.emittedBy, 'is fully valid');
                  7 } else if (field.isPotentiallyValid) {
                  8 console.log(event.emittedBy, 'is potentially valid');
                  9 } else {
                  10 console.log(event.emittedBy, 'is not valid');
                  11 }
                  12 });
                  13});

                  inputSubmitRequest

                  This event triggers when the user requests submission of an input field, by pressing the Enter or Return key on their keyboard, or mobile equivalent.

                    1var hostedFields = require('braintree-web/hosted-fields');
                    2var submitButton = document.querySelector('input[type="submit"]');
                    3
                    4paypal.HostedFields.render({ /* ... */ }).then(function (hostedFieldsInstance) {
                    5 hostedFieldsInstance.on('inputSubmitRequest', function () {
                    6 // User requested submission, e.g. by pressing Enter or equivalent
                    7 submitButton.click();
                    8 });
                    9});

                    Methods

                    render()

                      1render(options){Promise|void}

                      The render() method creates an instance of advanced credit and debit card payments and renders the card fields for checkout based on the mapping and styles provided by options. Includes the following parameters:

                      ParameterTypeDescription
                      optionsobjectThe options are used to control the mapping of the HTML element to the advanced credit and debit card payments inputs, style, and properties of each of the advanced credit and debit card payments inputs.
                      createOrder: A callback field that returns the order-id value. The order-id is an essential reference ID to each order that is created. It is also used to associate the card details entered to the order created.
                      styles: A styleOptions parameter that defines the styling applied on each of the advanced credit and debit card payments inputs .
                      fields: A fieldOptions parameter that defines the mapping of the HTML element to the advanced credit and debit card payments inputs and their properties.

                      isEligible()

                        1isEligible(){boolean}

                        The isEligible() method checks if advanced credit and debit card payments are eligible to render, based on configuration and business rules.

                        addClass()

                          1addClass(field, classname, callback<sub>opt</sub>) → {Promise|void}

                          The addClass1() method adds a class to a field. It is useful for updating field styles when events occur elsewhere in your checkout integration. Includes the following parameters:

                          ParameterTypeDescription
                          fieldstringThe field you want to add a class to. Must be a valid fieldOption.
                          classnamestringThe class to be added.
                          callbackcallbackCallback executed on completion, containing an error if one occurred. No data is returned if the class is added successfully.

                          clear()

                            1clear(field, callback<sub>opt</sub>) → {Promise|void}

                            The clear() method clears the value of a field. Includes the following parameters:

                            ParameterTypeDescription
                            fieldstringThe field you want to clear. Must be a valid fieldOption.
                            callbackcallbackCallback executed on completion, containing an error if one occurred. No data is returned if the class is added successfully.

                            focus()

                              1focus(field, callback<sub>opt</sub>) → {void}

                              The focus() method programmatically focuses a field. Includes the following parameters:

                              ParameterTypeDescription
                              fieldstringThe field you want to focus. Must be a valid fieldOption.
                              callbackcallbackCallback executed on completion, containing an error if one occurred. No data is returned if the class is added successfully.

                              getState()

                                1getState(){object}

                                The getState() method returns an object that includes the state of all fields and possible card types.

                                on()

                                  1on(event, handler){void}

                                  The on() method subscribes a handler function to a named event. Events include:

                                  • blur
                                  • focus
                                  • empty
                                  • notEmpty
                                  • cardTypeChange
                                  • validityChange

                                  Events trigger a stateObject. Includes the following parameters:

                                  ParameterTypeDescription
                                  eventstringThe name of the event to which you are subscribing.
                                  handlercallbackA callback to handle the event.

                                  removeAttribute()

                                    1removeAttribute(options, callback<sub>opt</sub>) → {Promise|void}

                                    The removeAttribute() method removes a supported attribute from a field. Includes the following parameters:

                                    ParameterTypeDescription
                                    optionsobjectThe options for the attribute you want to remove.
                                    field: A string field from which you want to remove an attribute. Must be a valid fieldOption.
                                    attribute: The name of the attribute you want to remove from the field.
                                    callbackcallbackCallback executed on completion, containing an error if one occurred. No data is returned if the attribute is removed successfully.

                                    setAttribute()

                                      1setAttribute(options, callback<sub>opt</sub>) → {Promise|void}

                                      The setAttribute() method sets an attribute of a field. Supported attributes are aria-invalid, aria-required, disabled, and placeholder. Includes the following parameters:

                                      ParameterTypeDescription
                                      optionsobjectThe options for the attribute you want to set.
                                      field: A string field from which you want to add an attribute. Must be a valid fieldOption.
                                      attribute: The name of the attribute you want to add to the field.
                                      - value: The value for the attribute.
                                      callbackcallbackCallback executed on completion, containing an error if one occurred. No data is returned if the class is added successfully.

                                      removeClass()

                                        1removeClass(field, classname, callback<sub>opt</sub>) → {Promise|void}

                                        The removeClass() method removes a class to a field. Useful for updating field styles when events occur elsewhere in your checkout integration. Includes the following parameters:

                                        ParameterTypeDescription
                                        fieldstringThe field you want to remove a class from. Must be a valid fieldOption.
                                        classnamestringThe class to be removed.
                                        callbackcallbackCallback executed on completion, containing an error if one occurred. No data is returned if the class is added successfully.

                                        setMessage()

                                          1setMessage(options){void}

                                          The setMessage() method sets a visually hidden message for screen readers on a field. Includes the following parameter:

                                          ParameterTypeDescription
                                          optionsobjectThe options for the attribute you want to set.
                                          field: A string field from which you want to add an attribute. Must be a valid fieldOption.
                                          message: The message to set.

                                          Type definitions

                                          field

                                          Fields used in fieldOptions object.

                                          PropertyTypeDescription
                                          selectorstringA CSS selector to find the container where the card fields are inserted.
                                          placeholderstringUsed as the placeholder attribute of the input. If placeholder is not natively supported by the browser, it will be polyfilled.
                                          typestringThe type attribute of the input. To mask CVV input, for instance, use type: "password".
                                          formatInputbooleanEnable or disable automatic formatting on this field. Default is true.
                                          maskInputobject or booleanEnable or disable input masking when input is not focused. If set to true, instead of an object, the defaults for the maskInput parameters are used. Default is false. The object properties are:
                                          character: A string field which specifies the character to use when masking the input. The default character ('•') uses a unicode symbol, so the web page must support UTF-8 characters when using the default.
                                          showLastFour: A boolean field which is applicable only for the credit card field. Defines whether or not to show the last 4 digits of the card when masking. Default is false.
                                          maxCardLengthnumberThis option applies only to the number field. Allows a limit to the length of the card number, even if the card brand might support numbers of a greater length. If the value passed is greater than the max length for a card brand, the smaller number of the two values is used. For example, if maxCardLength is set to 16, but an American Express card, which has a max card length of 15, is entered, a max card length of 15 is used.
                                          maxlengthnumberThis option applies only to the cvv field. Used as the maxlength attribute of the input if it is less than the default. The primary use cases for the maxlength option are: limiting the length of the CVV input for CVV-only verifications when the card type is known, and limiting the length of the postal code input when cards are coming from a known region.
                                          minlengthnumberThis option applies only to the cvv field. Used as the minlength attribute of the input. The default value is 3. The minlength attribute applies only to integrations capturing a CVV without a number field.
                                          prefillstringA value to pre-fill the field with. For example, when creating an update card form, you can pre-fill the expiration date fields with the old expiration date data.
                                          rejectUnsupportedCardsbooleanAllow only card types that your merchant account is able to process. Unsupported card types will invalidate the card form. For example, if you process only Visa cards, a customer entering an American Express card would get an invalid card field. This can be used only for the number field. The default is false.

                                          fieldOptions

                                          An object that has field objects for each field. Used in render() method.

                                          PropertyTypeDescription
                                          numberobject fieldA field for card number.
                                          expirationDateobject fieldA field for expiration date in MM/YYYY or MM/YY format.
                                          cvvobject fieldA field for 3 or 4 digit card verification code (like CVV or CID).

                                          styleOptions

                                          An object that represents CSS that is applied in each card field. This object looks similar to CSS. Typically, these styles involve fonts such as font-family or color.

                                          You can also pass the name of a class on your site that contains the styles you want to apply. The style properties are automatically pulled off the class and applied to the card field inputs.

                                          cardSecurityCode

                                          Information about the security code for a card.

                                          PropertyTypeDescription
                                          namestringThe name of security code for card CVV CID CVC
                                          sizenumberThe expected length of the security code. Typically, this is 3 or 4.

                                          hostedFieldsCard

                                          Information about the card type, sent in stateObjects.

                                          PropertyTypeDescription
                                          typestringThe code-friendly representation of the card type. Can be one of the following strings:
                                          american-express
                                          diners-club
                                          discover
                                          jcb
                                          maestro
                                          master-card
                                          unionpay
                                          visa
                                          niceTypestringThe pretty-printed card type. Can be one of the following strings:
                                          American Express
                                          Diners Club
                                          Discover
                                          JCB
                                          Maestro
                                          MasterCard
                                          UnionPay
                                          Visa
                                          codeobject cardSecurityCodeThis object contains data relevant to the security code requirements of the card brand. For example, on a Visa card there will be a CVV of 3 digits, whereas an American Express card requires a 4-digit CID.

                                          hostedFieldsFieldData

                                          Fields data for advanced credit and debit card payments is sent in stateObjects.

                                          PropertyTypeDescription
                                          containerHTML elementReference to the container DOM element on your page associated with the current event.
                                          isFocusedbooleanWhether or not the input is currently focused.
                                          isEmptybooleanWhether or not the user has entered a value in the input.
                                          isPotentiallyValidbooleanA determination based on the future validity of the input value. This is helpful when a user is entering a card number and types "41". While that value is not valid for submission, it is still possible for it to become a fully qualified entry. However, if the user enters "4x" it is clear that the card number can never become valid and isPotentiallyValid will return false.
                                          isValidbooleanWhether or not the value of the associated input is fully qualified for submission.

                                          stateObject

                                          The event payload is sent from on or getState.

                                          PropertyTypeDescription
                                          cardsarrayReturns an array of potential cards. If the card type has been determined, the array will contain only one card. Internally, advanced credit and debit card payments uses credit-card-type, an open-source card detection library.
                                          emittedBystringThe name of the field associated with an event. This is not included if returned by getState. It will be one of the following strings:
                                          "number"
                                          "cvv"
                                          "expirationDate"
                                          fieldsobject hostedFieldsFieldDataContains data about the field in context of the event. The field in context can be,
                                          "number"
                                          "cvv"
                                          "expirationDate"

                                          We use cookies to improve your experience on our site. May we use marketing cookies to show you personalized ads? Manage all cookies