JavaScript API Reference
This reference provides details about the JavaScript API for creating Microform Integration web pages.
Class: Field
An instance of this class is returned when you add a Field to a Microform integration using microform.createField. With this object, you can then interact with the Field to subscribe to events, programmatically set properties in the Field, and load it to the DOM.
Methods
clear()
Programmatically clear any entered value within the field.
Example
field.clear();dispose()
Permanently remove this field from your Microform integration.
Example
field.dispose();focus()
Programmatically set user focus to the Microform input field.
Example
field.focus();load(container)
Load this field into a container element on your page.
Successful loading of this field triggers a load event.
| Name | Type | Description |
|---|---|---|
| container | HTMLElement | string | Location in which to load this field. It can be either an HTMLElement reference or a CSS selector string that is used to load the element. |
Examples
Using a CSS selector
field.load('.form-control.card-number');Using an HTML element
const container = document.getElementById('container');field.load(container);off(type, listener)
Unsubscribe an event handler from a Microform Field.
| Name | Type | Description |
|---|---|---|
| type | string | Name of the event you wish to unsubscribe from. |
| listener | function | The handler you wish to be unsubscribed. |
Example
// subscribe to an event using .on() but keep a reference to the handler that was supplied.const focusHandler = function() { console.log('focus received'); }field.on('focus', focusHandler);// then at a later point you can remove this subscription by supplying the same arguments to .off()field.off('focus', focusHandler);on(type, listener)
Subscribe to events emitted by a Microform Field. Supported eventTypes are:
autocompleteblurchangefocusinputSubmitRequestloadunloadupdate
Some events might return data as the first parameter to the callback; otherwise this is undefined. For further details see each event's documentation using the links above.
| Name | Type | Description |
|---|---|---|
| type | string | Name of the event you wish to subscribe to. |
| listener | function | Handler to execute when event is triggered. |
Example
field.on('focus', function() { console.log('focus received'); });unload()
Remove the Field from the Document Object Model (DOM). This is the opposite of a load operation.
Example
field.unload();update(options)
Update the field with new configuration options. This accepts the same parameters as microform.createField(). New options are merged into the existing configuration of the field.
| Name | Type | Description |
|---|---|---|
| options | object | New options to be merged with previous configuration. |
Example
// field initially loaded as disabled with no placeholderconst number = microform.createField('number', { disabled: true });number.load('#container');// enable the field and set placeholder textnumber.update({ disabled: false, placeholder: 'Please enter your card number' });Events
autocomplete
Emitted when a customer has used a browser or third-party tool to perform an autocomplete/autofill on the input field. Microform attempts to capture additional information from the autocompletion and supply these to the callback if available. Possible additional values returned are:
expirationMonthexpirationYearname
If a value has not been supplied in the autocompletion, it is undefined in the callback data. As such, verify that it exists before use.
Examples
Possible format of data supplied to callback
{ "name": "_____", "expirationMonth": "__", "expirationYear": "____"}Updating the rest of your checkout after an autocomplete event
field.on('autocomplete', function(data) {if (data.name) document.querySelector('#myName').value = data.name;if (data.expirationMonth) document.querySelector('#myMonth').value = data.expirationMonth;if (data.expirationYear) document.querySelector('#myYear').value = data.expirationYear;});blur
This event is emitted when the input field has lost focus.
Example
field.on('blur', function() { console.log('Field has lost focus');});// focus the field in the browser then un-focus the field to see your supplied handler executechange
Emitted when some state has changed within the input field. The payload for this event contains several properties.
Type: object
| Name | Type |
|---|---|
| card | object |
| valid | boolean |
| couldBeValid | boolean |
| empty | boolean |
Examples
Minimal example:
field.on('change', function(data) { console.log('Change event!'); console.log(data);});Use the card detection result to update your UI.
const cardImage = document.querySelector('img.cardDisplay');const cardSecurityCodeLabel = document.querySelector('label[for=securityCode]');// create an object to map card names to the URL of your custom imagesconst cardImages = { visa: '/your-images/visa.png', mastercard: '/your-images/mastercard.png', amex: '/your-images/amex.png', maestro: '/your-images/maestro.png', discover: '/your-images/discover.png', dinersclub: '/your-images/dinersclub.png', jcb: '/your-images/jcb.png'};field.on('change', function(data) { if (data.card.length === 1) { // use the card name to set the correct image src cardImage.src = cardImages[data.card[0].name]; // update the security code label to match the detected card's naming convention cardSecurityCodeLabel.textContent = data.card[0].securityCode.name; } else { // show a generic card image cardImage.src = '/your-images/generic-card.png'; }});Use the card detection result to filter select element in another part of your checkout.
const cardTypeOptions = document.querySelector('select[name=cardType] option');field.on('change', function(data) { // extract the identified card types const detectedCardTypes = data.card.map(function(c) { return c.cybsCardType; }); // disable any select options not in the detected card types list cardTypeOptions.forEach(function (o) { o.disabled = detectedCardTypes.includes(o.value); });});Updating validation styles on your form element.
const myForm = document.querySelector('form');field.on('change', function(data) { myForm.classList.toggle('cardIsValidStyle', data.valid); myForm.classList.toggle('cardCouldBeValidStyle', data.couldBeValid);});focus
Emitted when the input field has received focus.
Example
field.on('focus', function() { console.log('Field has received focus');});// focus the field in the browser to see your supplied handler executeinputSubmitRequest
Emitted when a customer has requested submission of the input by pressing Return key or similar. By subscribing to this event you can easily replicate the familiar user experience of pressing enter to submit a form. Shown below is an example of how to implement this. The inputSubmitRequest handler will:
- Call Microform.createToken(). For more information, see these topics:
- Take the result and add it to a hidden input on your checkout.
- Trigger submission of the form containing the newly created token for you to use server-side.
Example
const form = document.querySelector('form');const hiddenInput = document.querySelector('form input[name=token]');field.on('inputSubmitRequest', function() { const options = { // }; microform.createToken(options, function(response) { hiddenInput.value = response.token; form.submit(); });});load
This event is emitted when the field has been fully loaded and is ready for user input.
Example
field.on('load', function() { console.log('Field is ready for user input');});unload
This event is emitted when the field has been unloaded and no longer available for user input.
Example
field.on('unload', function() { console.log('Field has been removed from the DOM');});update
This event is emitted when the field has been updated. The event data contains the settings that were successfully applied during this update.
Type: object
Example
field.on('update', function(data) { console.log('Field has been updated. Changes applied were:'); console.log(data);});Module: FLEX
Flex(captureContext)
new Flex(captureContext)
For detailed setup instructions, see Getting Started.
Parameters:
| Name | Type | Description |
|---|---|---|
captureContext | String | JSON Web Token (JWT) string requested through a server-side authenticated call before the checkout flow starts. |
Example
Basic Setup
<script src="[INSERT clientLibrary VALUE HERE]" integrity="[INSERT clientLibraryIntegrity VALUE HERE]" crossorigin="anonymous"></script><!-- Note: Script location and integrity value should be sourced from the capture context response clientLibrary and clientLibraryIntegrity values. --><script> const flex = new Flex('captureContext');</script>Methods
microform(optionsopt) > {Microform}
This method is the main setup function used to initialize Microform Integration. Upon successful setup, the callback receives a microform, which is used to interact with the service and build the integration. For details, see Class: Microform.
| Name | Type | Description |
|---|---|---|
options | Object |
| Name | Type | Attributes | Description |
|---|---|---|---|
styles | Object | <optional> | Apply custom styling to all the fields in your integration. |
Returns:
Type: Microform
Examples
Minimal Setup
const flex = new Flex('header.payload.signature');const microform = flex.microform();Custom Styling
const flex = new Flex('header.payload.signature');const microform = flex.microform({ styles: { input: { color: '#212529', 'font-size': '20px' } }});Class: Microform
An instance of this class is returned when you create a Microform integration using flex.microform. This object allows the creation of Microform Fields. For details, see Module: Flex.
Methods
createField(fieldType, optionsopt) > {Field}
Creates a field for this Microform integration.
Parameters
| Name | Type | Attributes | Description |
|---|---|---|---|
fieldType | string | Supported values: number securityCode | |
options | object | <optional> | These options can be changed after initialization using field.update(). |
Properties
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
aria-label | string | <optional> | true | Sets the input's label for use by assistive technologies using the aria-label attribute. |
aria-required | boolean | <optional> | true | Used to indicate through assistive technologies that this input is required for submission using the aria-required attribute. |
autoformat | Boolean | <optional> | true | Enables or disables automatic formatting of the input field. This is only supported for number fields and automatically inserts spaces based on the detected card type. |
description | string | <optional> | Sets the input's description for use by assistive technologies using the aria-describedby attribute. | |
disabled | Boolean | <optional> | false | Sets the disabled attribute on the input. |
maxLength | number | <optional> | 3 | Sets the maximum length attribute on the input. This is only supported for securityCode fields and might take a value of 3 or 4. |
placeholder | string | <optional> | Sets the placeholder attribute on the input. | |
styles | stylingOptions | <optional> | Applies custom styling to this field. | |
title | string | <optional> | Sets the title attribute on the input. Typically used to display tooltip text on hover. |
Returns
Type: Field
Examples
Minimal Setup
const flex = new Flex('.........');const microform = flex.microform('card');const number = microform.createField('number');Providing Custom Styles
const flex = new Flex('.........');const microform = flex.microform();const number = microform.createField('number', { styles: { input: { 'font-family': '"Courier New", monospace' } }});Providing Custom Styles to All Fields within the Microform Integration
const flex = new Flex('.........');// apply styles to all fieldsconst microform = flex.microform('card', { styles: customStyles });// override the text color for the card number field onlyconst number = microform.createField('number', { styles: { input: { color: '#000' }}});Providing Custom Styles to A Specific Field within the Microform Integration
const flex = new Flex('.........');const microform = flex.microform('card');const number = microform.createField('number', { styles: { input: { 'font-family': '"Courier New", monospace' } }});Setting the Length of a Security Code Field
const flex = new Flex('.........');const microform = flex.microform('card');const securityCode = microform.createField('securityCode', {maxLength: 4});createToken(options, callback)
Requests a token using the card data captured in the Microform fields. A successful token creation receives a transient token as its second callback parameter.
Parameter
| Name | Type | Description |
|---|---|---|
options | object | Additional tokenization options. |
callback | callback | Any error is returned as the first callback parameter. Any successful creation of a token is returned as a string in the second parameter. |
Properties
| Name | Type | Attributes | Description |
|---|---|---|---|
type | string | <optional> | Three-digit card type string. If set, this overrides any automatic card detection. |
expirationMonth | string | <optional> | Two-digit month string. Must be padded with leading zeros if single digit. |
expirationYear | string | <optional> | Four-digit year string. |
Examples
Minimal example omitting all optional parameters.
microform.createToken({}, function(err, token) { if (err) { console.error(err); return; } console.log('Token successfully created!'); console.log(token);});Override the cardType parameter using a select element that is part of your checkout.
// Assumes your checkout has a select element with option values that are card type codes:// <select id="cardTypeOverride">// <option value="001">Visa</option>// <option value="002">Mastercard</option>// <option value="003">American Express</option>// etc...// </select>const options = { type: document.querySelector('#cardTypeOverride').value};microform.createToken(options, function(err, token) { // handle errors & token response});Handling error scenarios
microform.createToken(options, function(err, token) { if (err) { switch (err.reason) { case 'CREATE_TOKEN_NO_FIELDS_LOADED': break; case 'CREATE_TOKEN_TIMEOUT': break; case 'CREATE_TOKEN_NO_FIELDS': break; case 'CREATE_TOKEN_VALIDATION_PARAMS': break; case 'CREATE_TOKEN_VALIDATION_FIELDS': break; case 'CREATE_TOKEN_VALIDATION_SERVERSIDE': break; case 'CREATE_TOKEN_UNABLE_TO_START': break; default: console.error('Unknown error'); break; } } else { console.log('Token created: ', token); }});Class: MicroformError
This class defines how error scenarios are presented by Microform, primarily as the first argument to callbacks. See callback(erropt, nullable, dataopt, nullable) > {void}.
Members
(static, readonly)Reason Codes - Field Load Errors
Possible errors that can occur during the loading or unloading of a field.
Properties
| Name | Type | Description |
|---|---|---|
| FIELD_UNLOAD_ERROR | string | Occurs when you attempt to unload a field that is not currently loaded. |
| FIELD_ALREADY_LOADED | string | Occurs when you attempt to load a field which is already loaded. |
| FIELD_LOAD_CONTAINER_SELECTOR | string | Occurs when a Document Object Model (DOM) element cannot be located using the supplied CSS Selector string. |
| FIELD_LOAD_INVALID_CONTAINER | string | Occurs when an invalid container parameter has been supplied. |
| FIELD_SUBSCRIBE_UNSUPPORTED_EVENT | string | Occurs when you attempt to subscribe to an unsupported event type. |
| FIELD_SUBSCRIBE_INVALID_CALLBACK | string | Occurs when you supply a callback that is not a function. |
(static, readonly)Reason Codes - Field object Creation
Possible errors that can occur during the creation of a Field object createField(fieldType, optionsopt) > {Field}.
Properties
| Name | Type | Description |
|---|---|---|
| CREATE_FIELD_INVALID_FIELD_TYPE | string | Occurs when you try to create a field with an unsupported type. |
| CREATE_FIELD_DUPLICATE | string | Occurs when a field of the given type has already been added to the integration. |
(static, readonly)Reason Codes - Flex object Creation
Possible errors that can occur during the creation of a Flex object.
Properties
| Name | Type | Description |
|---|---|---|
| CAPTURE_CONTEXT_INVALID | string | Occurs when you pass an invalid JWT. |
| CAPTURE_CONTEXT_EXPIRED | string | Occurs when the JWT you pass has expired. |
(static, readonly)Reason Codes - Iframe validation errors
Possible errors that can occur during the loading of an iframe.
Properties
| Name | Type | Description |
|---|---|---|
| IFRAME_JWT_VALIDATION_FAILED | string | Occurs when the iframe cannot validate the JWT passed. |
| IFRAME_UNSUPPORTED_FIELD_TYPE | string | Occurs when the iframe is attempting to load with an invalid field type. |
(static, readonly)Reason Codes - Token creation
Possible errors that can occur during the request to create a token.
Properties
| Name | Type | Description |
|---|---|---|
| CREATE_TOKEN_NO_FIELDS_LOADED | string | Occurs when you try to request a token, but no fields have been loaded. |
| CREATE_TOKEN_TIMEOUT | string | Occurs when the createToken call was unable to proceed within Capture Context Validity (15 mins): Do not resend the capture context or reload Microform. Instruct the customer to retry until successful. After Capture Context Validity (>15 mins): Resend the capture context request and reload Microform. |
| CREATE_TOKEN_XHR_ERROR | string | Occurs when there is a network error when attempting to create a token. Resend the capture context request and reload Microform. |
| CREATE_TOKEN_NO_FIELDS | string | Occurs when the data fields are unavailable for collection. |
| CREATE_TOKEN_VALIDATION_PARAMS | string | Occurs when there is an issue with parameters supplied to createToken. |
| CREATE_TOKEN_VALIDATION_FIELDS | string | Occurs when there is a validation issue with data in the loaded fields. Instruct the customer to enter valid data. |
| CREATE_TOKEN_VALIDATION_SERVERSIDE | string | Occurs when server-side validation rejects the createToken request. |
| CREATE_TOKEN_UNABLE_TO_START | string | Occurs when no loaded field was able to handle the createToken request. |
(nullable)correlationID :string
The correlationId of any underlying API call that resulted in this error.
Type
String
(nullable)details :array
Additional error-specific information.
Type
Array
(nullable)informationLink :string
A URL to general online documentation for this error.
Type
String
message :string
A simple human-readable description of the error that has occurred.
Type
String
reason :string
A reason corresponding to the specific error that has occurred.
Type
String
Global
Type Definitions
callback(erropt, nullable, dataopt, nullable) > {void}
Microform uses the error-first callback pattern, as commonly used in Node.js.
If an error occurs, it is returned by the first err argument of the callback. If no error occurs, err has a null value and any return data is provided in the second argument.
Parameters
| Name | Type | Attributes | Description |
|---|---|---|---|
| err | MicroformError. See Class: MicroformError. | <optional> <nullable> | An Object detailing occurred errors, otherwise null. |
| data | * | <optional> <nullable> | In success scenarios, this is whatever data has been returned by the asynchronous function call, if any. |
Returns
Type: void
Example
This example shows how to make use of this style of error handling in your code:
foo(function (err, data) { // check for and handle any errors if (err) throw err; // otherwise use the data returned console.log(data);});StylingOptions
Styling options are supplied as an object that resembles CSS but is limited to a subset of CSS properties that relate only to the text within the iframe.
These CSS selectors are supported:
input::placeholder:hover:focus:disabledvalidinvalidincomplete
These CSS properties are supported:
colorcursorfontfont-familyfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-alternatesfont-variant-capsfont-variant-east-asianfont-variant-ligaturesfont-variant-numericfont-weightincompleteline-heightopacitytext-shadowtext-renderingtransition-moz-osx-font-smoothing-moz-tap-highlight-color-moz-transition-o-transition-webkit-font-smoothing-webkit-tap-highlight-color-webkit-transition
Any unsupported properties are not applied and raise a console.warn() alert.
Properties
| Name | Type | Attributes | Description |
|---|---|---|---|
input | object | <optional> | Main styling applied to the input field. |
::placeholder | object | <optional> | Styles for the ::placeholder pseudo-element within the main input field. This also adds vendor prefixes for supported browsers. |
:hover | object | <optional> | Styles to apply when the input field is hovered over. |
:focus | object | <optional> | Styles to apply when the input field has focus. |
:disabled | object | <optional> | Styles applied when the input field has been disabled. |
valid | object | <optional> | Styles applied when Microform detects that the input card number is valid. Relies on card detection being enabled. |
invalid | object | <optional> | Styles applied when Microform detects that the input card number is invalid. Relies on card detection being enabled. |
Example
const styles = { 'input': { 'color': '#464646', 'font-size': '16px', 'font-family': 'monospace' }, ':hover': { 'font-style': 'italic' }, 'invalid': { 'color': 'red' }};Thanks for your feedback!
Last published: September 29, 2026