HostedFields

HostedFields

This class represents a Hosted Fields component produced by braintree-web/hosted-fields.create. Instances of this class have methods for interacting with the input fields within Hosted Fields' iframes.

Constructor

new HostedFields(options)

Do not use this constructor directly. Use braintree-web.hosted-fields.create instead.

Parameters:
Name Type Description
options object

The Hosted Fields create options.

Source:

Methods

addClass(field, classname, callbackopt) → {Promise|void}

Add a class to a field. Useful for updating field styles when events occur elsewhere in your checkout.

Parameters:
Name Type Attributes Description
field string

The field you wish to add a class to. Must be a valid fieldOption.

classname string

The class to be added.

callback callback <optional>

Callback executed on completion, containing an error if one occurred. No data is returned if the class is added successfully.

Source:
Example
hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr) {
  if (addClassErr) {
    console.error(addClassErr);
  }
});

clear(field, callbackopt) → {Promise|void}

Clear the value of a field.

Parameters:
Name Type Attributes Description
field string

The field you wish to clear. Must be a valid fieldOption.

callback callback <optional>

Callback executed on completion, containing an error if one occurred. No data is returned if the field cleared successfully.

Source:
Examples
hostedFieldsInstance.clear('number', function (clearErr) {
  if (clearErr) {
    console.error(clearErr);
  }
});

Clear several fields

hostedFieldsInstance.clear('number');
hostedFieldsInstance.clear('cvv');
hostedFieldsInstance.clear('expirationDate');

focus(field, callbackopt) → {void}

Programmatically focus a field.

Parameters:
Name Type Attributes Description
field string

The field you want to focus. Must be a valid fieldOption.

callback callback <optional>

Callback executed on completion, containing an error if one occurred. No data is returned if the field focused successfully.

Source:
Examples
hostedFieldsInstance.focus('number', function (focusErr) {
  if (focusErr) {
    console.error(focusErr);
  }
});

Using an event listener

myElement.addEventListener('click', function (e) {
  // In Firefox, the focus method can be suppressed
  //   if the element has a tabindex property or the element
  //   is an anchor link with an href property.
  // In Mobile Safari, the focus method is unable to
  //   programatically open the keyboard, as only
  //   touch events are allowed to do so.
  e.preventDefault();
  hostedFieldsInstance.focus('number');
});

getState() → {object}

Returns an object that includes the state of all fields and possible card types.

Source:
Example

Check if all fields are valid

var state = hostedFieldsInstance.getState();

var formValid = Object.keys(state.fields).every(function (key) {
  return state.fields[key].isValid;
});

on(event, handler) → {void}

Subscribes a handler function to a named event. event should be blur, focus, empty, notEmpty, cardTypeChange, validityChange, or inputSubmitRequest. Events will emit a stateObject.

Parameters:
Name Type Description
event string

The name of the event to which you are subscribing.

handler function

A callback to handle the event.

Source:
Example

Listening to a Hosted Field event, in this case 'focus'

hostedFields.create({ ... }, function (createErr, hostedFieldsInstance) {
  hostedFieldsInstance.on('focus', function (event) {
    console.log(event.emittedBy, 'has been focused');
  });
});

removeAttribute(options, callbackopt) → {Promise|void}

Removes a supported attribute from a field.

Parameters:
Name Type Attributes Description
options object

The options for the attribute you wish to remove.

Properties
Name Type Description
field string

The field from which you wish to remove an attribute. Must be a valid fieldOption.

attribute string

The name of the attribute you wish to remove from the field.

callback callback <optional>

Callback executed on completion, containing an error if one occurred. No data is returned if the attribute is removed successfully.

Source:
Example

Remove the placeholder attribute of a field

hostedFieldsInstance.removeAttribute({
  field: 'number',
  attribute: 'placeholder'
}, function (attributeErr) {
  if (attributeErr) {
    console.error(attributeErr);
  }
});

removeClass(field, classname, callbackopt) → {Promise|void}

Removes a class to a field. Useful for updating field styles when events occur elsewhere in your checkout.

Parameters:
Name Type Attributes Description
field string

The field you wish to remove a class from. Must be a valid fieldOption.

classname string

The class to be removed.

callback callback <optional>

Callback executed on completion, containing an error if one occurred. No data is returned if the class is removed successfully.

Source:
Example
hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr) {
  if (addClassErr) {
    console.error(addClassErr);
    return;
  }

  // some time later...
  hostedFieldsInstance.removeClass('number', 'custom-class');
});

setAttribute(options, callbackopt) → {Promise|void}

Sets an attribute of a field. Supported attributes are aria-invalid, aria-required, disabled, and placeholder.

Parameters:
Name Type Attributes Description
options object

The options for the attribute you wish to set.

Properties
Name Type Description
field string

The field to which you wish to add an attribute. Must be a valid fieldOption.

attribute string

The name of the attribute you wish to add to the field.

value string

The value for the attribute.

callback callback <optional>

Callback executed on completion, containing an error if one occurred. No data is returned if the attribute is set successfully.

Source:
Examples

Set the placeholder attribute of a field

hostedFieldsInstance.setAttribute({
  field: 'number',
  attribute: 'placeholder',
  value: '1111 1111 1111 1111'
}, function (attributeErr) {
  if (attributeErr) {
    console.error(attributeErr);
  }
});

Set the aria-required attribute of a field

hostedFieldsInstance.setAttribute({
  field: 'number',
  attribute: 'aria-required',
  value: true
}, function (attributeErr) {
  if (attributeErr) {
    console.error(attributeErr);
  }
});

setMessage(options) → {void}

Sets a visually hidden message (for screenreaders) on a field.

Parameters:
Name Type Description
options object

The options for the attribute you wish to set.

Properties
Name Type Description
field string

The field to which you wish to add an attribute. Must be a valid field.

message string

The message to set.

Source:
Examples

Set an error message on a field

hostedFieldsInstance.setMessage({
  field: 'number',
  message: 'Invalid card number'
});

Remove the message on a field

hostedFieldsInstance.setMessage({
  field: 'number',
  message: ''
});

setPlaceholder(field, placeholder, callbackopt) → {Promise|void}

Parameters:
Name Type Attributes Description
field string

The field whose placeholder you wish to change. Must be a valid fieldOption.

placeholder string

Will be used as the placeholder attribute of the input.

callback callback <optional>

Callback executed on completion, containing an error if one occurred. No data is returned if the placeholder updated successfully.

Deprecated:

Source:

teardown(callbackopt) → {Promise|void}

Cleanly remove anything set up by create.

Parameters:
Name Type Attributes Description
callback callback <optional>

Called on completion, containing an error if one occurred. No data is returned if teardown completes successfully. If no callback is provided, teardown returns a promise.

Source:
Example
hostedFieldsInstance.teardown(function (teardownErr) {
  if (teardownErr) {
    console.error('Could not tear down Hosted Fields!');
  } else {
    console.info('Hosted Fields has been torn down!');
  }
});

tokenize(optionsopt, callbackopt) → {Promise|void}

Tokenizes fields and returns a nonce payload.

Parameters:
Name Type Attributes Description
options object <optional>

All tokenization options for the Hosted Fields component.

Properties
Name Type Attributes Default Description
vault boolean <optional>
false

When true, will vault the tokenized card. Cards will only be vaulted when using a client created with a client token that includes a customer ID.

fieldsToTokenize array <optional>

By default, all fields will be tokenized. You may specify which fields specifically you wish to tokenize with this property. Valid options are 'number', 'cvv', 'expirationDate', 'expirationMonth', 'expirationYear', 'postalCode'.

cardholderName string <optional>

When supplied, the cardholder name to be tokenized with the contents of the fields.

billingAddress.postalCode string <optional>

When supplied, this postal code will be tokenized along with the contents of the fields. If a postal code is provided as part of the Hosted Fields configuration, the value of the field will be tokenized and this value will be ignored.

billingAddress.firstName string <optional>

When supplied, this customer first name will be tokenized along with the contents of the fields.

billingAddress.lastName string <optional>

When supplied, this customer last name will be tokenized along with the contents of the fields.

billingAddress.company string <optional>

When supplied, this company name will be tokenized along with the contents of the fields.

billingAddress.streetAddress string <optional>

When supplied, this street address will be tokenized along with the contents of the fields.

billingAddress.extendedAddress string <optional>

When supplied, this extended address will be tokenized along with the contents of the fields.

billingAddress.locality string <optional>

When supplied, this locality (the city) will be tokenized along with the contents of the fields.

billingAddress.region string <optional>

When supplied, this region (the state) will be tokenized along with the contents of the fields.

billingAddress.countryCodeNumeric string <optional>

When supplied, this numeric country code will be tokenized along with the contents of the fields.

billingAddress.countryCodeAlpha2 string <optional>

When supplied, this alpha 2 representation of a country will be tokenized along with the contents of the fields.

billingAddress.countryCodeAlpha3 string <optional>

When supplied, this alpha 3 representation of a country will be tokenized along with the contents of the fields.

billingAddress.countryName string <optional>

When supplied, this country name will be tokenized along with the contents of the fields.

callback callback <optional>

The second argument, data, is a tokenizePayload. If no callback is provided, tokenize returns a function that resolves with a tokenizePayload.

Source:
Examples

Tokenize a card

hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
  if (tokenizeErr) {
    switch (tokenizeErr.code) {
      case 'HOSTED_FIELDS_FIELDS_EMPTY':
        // occurs when none of the fields are filled in
        console.error('All fields are empty! Please fill out the form.');
        break;
      case 'HOSTED_FIELDS_FIELDS_INVALID':
        // occurs when certain fields do not pass client side validation
        console.error('Some fields are invalid:', tokenizeErr.details.invalidFieldKeys);

        // you can also programtically access the field containers for the invalid fields
        tokenizeErr.details.invalidFields.forEach(function (fieldContainer) {
          fieldContainer.className = 'invalid';
        });
        break;
      case 'HOSTED_FIELDS_TOKENIZATION_FAIL_ON_DUPLICATE':
        // occurs when:
        //   * the client token used for client authorization was generated
        //     with a customer ID and the fail on duplicate payment method
        //     option is set to true
        //   * the card being tokenized has previously been vaulted (with any customer)
        // See: https://developers.braintreepayments.com/reference/request/client-token/generate/#options.fail_on_duplicate_payment_method
        console.error('This payment method already exists in your vault.');
        break;
      case 'HOSTED_FIELDS_TOKENIZATION_CVV_VERIFICATION_FAILED':
        // occurs when:
        //   * the client token used for client authorization was generated
        //     with a customer ID and the verify card option is set to true
        //     and you have credit card verification turned on in the Braintree
        //     control panel
        //   * the cvv does not pass verfication (https://developers.braintreepayments.com/reference/general/testing/#avs-and-cvv/cid-responses)
        // See: https://developers.braintreepayments.com/reference/request/client-token/generate/#options.verify_card
        console.error('CVV did not pass verification');
        break;
      case 'HOSTED_FIELDS_FAILED_TOKENIZATION':
        // occurs for any other tokenization error on the server
        console.error('Tokenization failed server side. Is the card valid?');
        break;
      case 'HOSTED_FIELDS_TOKENIZATION_NETWORK_ERROR':
        // occurs when the Braintree gateway cannot be contacted
        console.error('Network error occurred when tokenizing.');
        break;
      default:
        console.error('Something bad happened!', tokenizeErr);
    }
  } else {
    console.log('Got nonce:', payload.nonce);
  }
});

Tokenize and vault a card

hostedFieldsInstance.tokenize({
  vault: true
}, function (tokenizeErr, payload) {
  if (tokenizeErr) {
    console.error(tokenizeErr);
  } else {
    console.log('Got nonce:', payload.nonce);
  }
});

Tokenize a card with cardholder name

hostedFieldsInstance.tokenize({
  cardholderName: 'First Last'
}, function (tokenizeErr, payload) {
  if (tokenizeErr) {
    console.error(tokenizeErr);
  } else {
    console.log('Got nonce:', payload.nonce);
  }
});

Tokenize a card with the postal code option

hostedFieldsInstance.tokenize({
  billingAddress: {
    postalCode: '11111'
  }
}, function (tokenizeErr, payload) {
  if (tokenizeErr) {
    console.error(tokenizeErr);
  } else {
    console.log('Got nonce:', payload.nonce);
  }
});

Tokenize a card with additional billing address options

hostedFieldsInstance.tokenize({
  billingAddress: {
    firstName: 'First',
    lastName: 'Last',
    company: 'Company',
    streetAddress: '123 Street',
    extendedAddress: 'Unit 1',
    // passing just one of the country options is sufficient to
    // associate the card details with a particular country
    // valid country names and codes can be found here:
    // https://developers.braintreepayments.com/reference/general/countries/ruby#list-of-countries
    countryName: 'United States',
    countryCodeAlpha2: 'US',
    countryCodeAlpha3: 'USA',
    countryCodeNumeric: '840'
  }
}, function (tokenizeErr, payload) {
  if (tokenizeErr) {
    console.error(tokenizeErr);
  } else {
    console.log('Got nonce:', payload.nonce);
  }
});

Type Definitions

hostedFieldsCard :object

Information about the card type, sent in stateObjects.

Properties:
Name Type Description
type string

The code-friendly representation of the card type. It will be one of the following strings:

  • american-express
  • diners-club
  • discover
  • jcb
  • maestro
  • master-card
  • unionpay
  • visa
niceType string

The pretty-printed card type. It will be one of the following strings:

  • American Express
  • Diners Club
  • Discover
  • JCB
  • Maestro
  • MasterCard
  • UnionPay
  • Visa
code object

This 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.

Properties
Name Type Description
name string

"CVV" "CID" "CVC"

size number

The expected length of the security code. Typically, this is 3 or 4.

Source:

hostedFieldsFieldData :object

Data about Hosted Fields fields, sent in stateObjects.

Properties:
Name Type Description
container HTMLElement

Reference to the container DOM element on your page associated with the current event.

isFocused boolean

Whether or not the input is currently focused.

isEmpty boolean

Whether or not the user has entered a value in the input.

isPotentiallyValid boolean

A 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.

isValid boolean

Whether or not the value of the associated input is fully qualified for submission.

Source:

stateObject :object

The event payload sent from on or getState.

Properties:
Name Type Description
cards Array.<HostedFields~hostedFieldsCard>

This will return an array of potential cards. If the card type has been determined, the array will contain only one card. Internally, Hosted Fields uses credit-card-type, an open-source card detection library.

emittedBy string

The name of the field associated with an event. This will not be included if returned by getState. It will be one of the following strings:

  • "number"
  • "cvv"
  • "expirationDate"
  • "expirationMonth"
  • "expirationYear"
  • "postalCode"
fields object
Properties
Name Type Attributes Description
number HostedFields~hostedFieldsFieldData <nullable>

hostedFieldsFieldData for the number field, if it is present.

cvv HostedFields~hostedFieldsFieldData <nullable>

hostedFieldsFieldData for the CVV field, if it is present.

expirationDate HostedFields~hostedFieldsFieldData <nullable>

hostedFieldsFieldData for the expiration date field, if it is present.

expirationMonth HostedFields~hostedFieldsFieldData <nullable>

hostedFieldsFieldData for the expiration month field, if it is present.

expirationYear HostedFields~hostedFieldsFieldData <nullable>

hostedFieldsFieldData for the expiration year field, if it is present.

postalCode HostedFields~hostedFieldsFieldData <nullable>

hostedFieldsFieldData for the postal code field, if it is present.

Source:

tokenizePayload :object

Properties:
Name Type Description
nonce string

The payment method nonce.

details object

Additional account details.

Properties
Name Type Description
bin string

The BIN number of the card.

cardType string

Type of card, ex: Visa, MasterCard.

lastFour string

Last four digits of card number.

lastTwo string

Last two digits of card number.

description string

A human-readable description.

type string

The payment method type, always CreditCard.

binData object

Information about the card based on the bin.

Properties
Name Type Description
commercial string

Possible values: 'Yes', 'No', 'Unknown'.

countryOfIssuance string

The country of issuance.

debit string

Possible values: 'Yes', 'No', 'Unknown'.

durbinRegulated string

Possible values: 'Yes', 'No', 'Unknown'.

healthcare string

Possible values: 'Yes', 'No', 'Unknown'.

issuingBank string

The issuing bank.

payroll string

Possible values: 'Yes', 'No', 'Unknown'.

prepaid string

Possible values: 'Yes', 'No', 'Unknown'.

productId string

The product id.

Source:

Events

blur :HostedFields~stateObject

This event is emitted when a field loses focus.

Source:
Example

Listening to a blur event

hostedFields.create({ ... }, function (createErr, hostedFieldsInstance) {
  hostedFieldsInstance.on('blur', function (event) {
    console.log(event.emittedBy, 'lost focus');
  });
});

cardTypeChange :HostedFields~stateObject

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

Source:
Example

Listening to a cardTypeChange event

hostedFields.create({ ... }, function (createErr, 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');
    }
  });
});

empty :HostedFields~stateObject

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

Source:
Example

Listening to an empty event

hostedFields.create({ ... }, function (createErr, hostedFieldsInstance) {
  hostedFieldsInstance.on('empty', function (event) {
    console.log(event.emittedBy, 'is now empty');
  });
});

focus :HostedFields~stateObject

This event is emitted when a field gains focus.

Source:
Example

Listening to a focus event

hostedFields.create({ ... }, function (createErr, hostedFieldsInstance) {
  hostedFieldsInstance.on('focus', function (event) {
    console.log(event.emittedBy, 'gained focus');
  });
});

inputSubmitRequest :HostedFields~stateObject

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

Source:
Example

Clicking a submit button upon hitting Enter (or equivalent) within a Hosted Field

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

hostedFields.create({ ... }, function (createErr, hostedFieldsInstance) {
  hostedFieldsInstance.on('inputSubmitRequest', function () {
    // User requested submission, e.g. by pressing Enter or equivalent
    submitButton.click();
  });
});

notEmpty :HostedFields~stateObject

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

Source:
Example

Listening to an notEmpty event

hostedFields.create({ ... }, function (createErr, hostedFieldsInstance) {
  hostedFieldsInstance.on('notEmpty', function (event) {
    console.log(event.emittedBy, 'is now not empty');
  });
});

validityChange :HostedFields~stateObject

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

Source:
Example

Listening to a validityChange event

hostedFields.create({ ... }, function (createErr, 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');
    }
  });
});