Subscribe to credit and debit card field events

DocsCurrentAdvancedLast updated: November 8th 2022, @ 12:41:15 pm


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:

paypal.HostedFields.render({ /* ... */ }).then(function (hostedFieldsInstance) {
 var cvvLabel = document.querySelector('label[for="cvv"]'); // The label for your CVV field

 hostedFieldsInstance.on('cardTypeChange', function (event) {
   // This event triggers when a change in card type is detected.
   // It triggers only from the number field.
   var cvvText;

   if (event.cards.length === 1) {
     cvvText = event.cards[0].code.name;
   } else {
     cvvText = 'CVV';
   }

   cvvLabel.innerHTML = cvvText;
   hostedFieldsInstance.setAttribute({
     field: 'cvv',
     attribute: 'placeholder',
     value: cvvText
   });
 });
});

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.

var form = document.querySelector('#my-sample-form');

paypal.HostedFields.render({ /* ... */ }).then(function (hostedFieldsInstance) {
  form.addEventListener('submit', function (event) {
    var state = hostedFieldsInstance.getState();
    var formValid = Object.keys(state.fields).every(function (key) {
      return state.fields[key].isValid;
    });

    if (formValid) {
      // Submit Hosted Fields card data
      hostedFieldsInstance.submit();
    } else {
      // Let the customer know their fields are invalid
    }
  });
});

Examples

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

focus

This event triggers when a field gains focus.

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

blur

This event triggers when a field loses focus.

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

empty

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

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

notEmpty

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

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

cardTypeChange

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

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

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.

paypal.HostedFields.render({ /* ... */ }).then(function (hostedFieldsInstance) {
  hostedFieldsInstance.on('validityChange', function (event) {
    var field = event.fields[event.emittedBy];

    if (field.isValid) {
      console.log(event.emittedBy, 'is fully valid');
    } else if (field.isPotentiallyValid) {
      console.log(event.emittedBy, 'is potentially valid');
    } else {
      console.log(event.emittedBy, 'is not valid');
    }
  });
});

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.

var hostedFields = require('braintree-web/hosted-fields');
var submitButton = document.querySelector('input[type="submit"]');

paypal.HostedFields.render({ /* ... */ }).then(function (hostedFieldsInstance) {
  hostedFieldsInstance.on('inputSubmitRequest', function () {
    // User requested submission, e.g. by pressing Enter or equivalent
    submitButton.click();
  });
});

Methods

render()

render(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()

isEligible() → {boolean}

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

addClass()

addClass(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()

clear(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()

focus(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()

getState() → {object}

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

on()

on(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()

removeAttribute(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()

setAttribute(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()

removeClass(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()

setMessage(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.

Note: Recommended for input elements only. If using a select for the expiration date, unexpected styling might occur.

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"