Reference Documentation

VGS Collect.js is a JavaScript library that enables you to gather data through any form securely. Quickly create custom forms that meet PCI, HIPAA, GDPR, or CCPA security standards. VGS intercepts sensitive data before it reaches your servers and replaces it with aliased versions, while securely storing the original data in our vault. The form fields operate like traditional forms but prevent access to unsecured data by embedding secure iframe components.

<script type="text/javascript" src="https://js.verygoodvault.com/vgs-collect/3.2.2/vgs-collect.js"></script>

VGSCollect.create()


Create a VGS Collect form instance.

VGSCollect.create(vaultId, environment, stateCallback)

Example:

const form = VGSCollect.create('tnt12345678', 'sandbox', (state) => {
    console.log(state);
  }
);

Parameters:

Argument
Type
Description

vaultId (required)

string

The VGS organization’s unique vault ID value.

environment (required)

string

Vault environment: sandbox, live or one with a specified data region (e.g live-eu-1 , live-ap-1).

stateCallback

(state) => {}

You have access to the form state object, which provides useful information about the field's condition.

State Object

The state object represents the current status of all fields mounted with VGS Collect.js. It provides a complete snapshot of the form, including validation results, completion status, and error messages.

Properties:

Property
Type
Description
Field Type Availability

isDirty

Boolean

Indicates whether the user has modified the field value.

All

isFocused

Boolean

Indicates whether the field is currently focused.

All

isValid

Boolean

Indicates whether the field value passes all validation rules.

All

isEmpty

Boolean

Indicates whether the field is empty.

All

isTouched

Boolean

Becomes true after the field has been blurred for the first time.

All

errorMessages

string[]

Contains an array of validation error messages for the field.

All

errors

object[]

An array of error objects associated with the field. Each object provides details about a specific validation error. See below section for additional context.

All

last4

string

Contains the last 4 digits of the entered value only when validation is successfully passed.

card-number, ssn

bin

string

Contains the Bank Identification Number (BIN) once the number is valid.

card-number

cardType

string

Represents the detected card brand (e.g., "visa", "mastercard", "amex"). See the list of supported card brands for details.

card-number

Errors Structure:

{
  "message": <string>,
  "details": {},
  "description": <string>,
  "code": 1001
}
  • message string A short, human-readable error message (e.g., "is required").

  • details object Additional metadata about the error. Contents vary depending on the validation rule.

  • description string A descriptive error string. Often duplicates message but may provide extended context.

  • code number A machine-readable error code identifying the type of validation failure (e.g., 1001 for “required”).

VGSCollect.subscribe()


Subscribe to the VGS Collect.js form instance events.

VGSCollect.subscribe(event, callback)

Example:

VGSCollect.subscribe('pluginScriptLoad', (pluginName, params, fields) => {});
VGSCollect.subscribe('fieldLoad', (field, form) => {});

Parameters:

Argument
Type
Description

event (required)

string

Event type:

  • pluginScriptLoad - Triggers after the third-party script (partner's script) has successfully loaded.

  • fieldLoad - Triggers every time a new field is added to the form.

callback

() ⇒ {}

A function to execute each time the event is triggered.

form.field()


Configure a secure input field. VGS Collect creates one iframe per input field:

form.field(selector, properties)

Example:

form.field('#space-for-my-field', {
  name: 'card-number', // required
  type: 'card-number', // required
  placeholder: 'Card number',
  validations: ['required', 'validCardNumber'],
  autoComplete: 'cc-number',
  css: {
    'color': '#31708f',
    'line-height': '1.5rem',
    'font-size': '24px',
  }
});

Parameters:

Argument
Type
Description

selector (required)

string

CSS selector that points to the DOM element where the iframe will be added.

properties (required)

object

Field properties.

General Properties
Property
Type
Description

name (required)

string

Name of the input field. Will be shown in the form state and used as a data key in the request payload.

type (required)

string

Type of the input field. Available field types: card-number, card-security-code, card-expiration-date, ssn, password, text, zip-code, postal-code, file, dropdown, checkbox.

validations

string[]

Validations that will be used to calculate the field isValid state.

css

object

An object of styles you can apply to the field.

placeholder

string

Input placeholder text.

autoComplete

string

Allows controlling how the browser should populate a given form field. The most common autocomplete attributes are: cc-name, cc-number, cc-csc, cc-exp, name, email, tel, shipping street-address, shipping locality, shipping region, shipping postal-code, shipping country

inputMode

string

Attribute that hints at the type of data that might be entered by the user while editing the element or its contents. This allows a browser to display an appropriate virtual keyboard.

classes

object

CSS classes that are applied to the container element when the field is in a particular state:

{
  'invalid': 'form__input--invalid', // the field is not valid
  'empty': 'form__input--empty', // the field is empty
  'focused': 'form__input--focused', // the field is focused
  'dirty': 'form__input--dirty', // interaction with the field happened
  'touched': 'form__input--touched', // the field has ever gained and lost focus
}

serializers

object[]

Change the format of the value being sent to the server.

// old - string is to be replaced with new value.
// new - string that replaces the specified substring.
// count - optional, defines how many times a certain string should be replaced.
{ name: 'replace', options: { old:' ', new:'-'', count: '2' }}

Card Number Properties
Property
Type
Description

showCardIcon

boolean

A small card icon will be shown on the right side of an input field. The icon will be changed based on the card brand.

icons

object

Unfortunately, we cannot use regular HTTP(s) URLs for security reasons. To customise an icon, you need to pass a{" "} Data URL with an icon. Check the example here.

  • cardPlaceholder

    • card icon for empty and undefined card brand states.

  • visa|amex|maestro|...

    • card icons for particular brands. Full list of types.

addCardBrands

object

Use it if you would like to extend the list of supported card brands or redefine existing card brand pattern. More information you can find here.

validCardBrands

[]

Use this property to allow only certain card brand types to be valid; for instance, you would like to accept Visa and Mastercard only. Assign validCardBrands The property to an array contains a list of supported cards in the following format:

{
  ...
  validCardBrands: [ { type: 'visa' }, { type: 'mastercard' }],
  ...
}
Card Security Code Properties
Property
Type
Description

showCardIcon

boolean

A small card icon will be shown on the right side of an input field. The icon will be changed based on the card brand.

icons

object

Unfortunately, we cannot use regular HTTP(s) URLs for security reasons. To customise an icon, you need to pass a{" "} Data URL with an icon. Check the example here.

  • cardPlaceholder

    • card icon for empty and undefined card brand states.

  • cvvFront

    • card icon for the front (Amex) CVV.

  • cvvBack

    • card icon for the back CVV.

Card Expiration Date Properties
Property
Type
Description

yearLength

number

Either 2 or 4. Control the length of the year we send to the server. If none is specified by default, we accept both formats.

separator

string

Separator to use between the month and year values. Default: " / ".

Text Properties
Property
Type
Description

min

number

Specifies the minimum value for an input element.

max

number

Specifies the minimum value for an input element.

maxLength

number

Maximum length (number of characters) of value.

step

number

Specifies the legal number intervals for an input element.

File Properties
Property
Type
Description

multiple

boolean

If present indicates that the user may choose more than one file.

accept

string[]

An array with one or more unique file type specifiers describing file types to allow. By default, set to ['images/*', '/pdf']. All available MIME types: image/png, image/apng, image/avif, image/gif, image/jpeg, image/svg+xml, image/svg, image/webp, image/*, .pdf, .csv

capture

string

String indicated what source to use for capturing image or video data: "user" | "environment".

maxFileSize

number

Defines maximum file size in Bytes. If the file size exceeds the specified number, you'll get the following error message in the form state: "uploaded file is too large".

maxFiles

number

Indicates maximum allowed file number. If the user uploads more than maxFiles value the form state will receive the following validation error: "maximum n files can be uploaded"

serializers

obejct[]

Convert file value to base64 format.

{ name: 'toBase64' }
Validation
Validation
Description
Associated errorMessage
Error Code

"required"

Checks if the field is not empty.

"is required"

1001

"validCardNumber"

Checks that the number is formatted correctly and passes the Luhn check.

"is not a valid card number"

1011

"validCardNumberExtended"

Under the hood extends the cards list with a new unknown card type which becomes valid once the value passes the Luhn check only and has at least 16 symbols.

"is not a valid card number"

1005

"validCardNumberLuhnCheck"

Checks if the card number is passing Luhn check only.

"is not a valid card number"

1004

"validCardSecurityCode"

Checks if the security code is valid based on the card number brand.

"is not a valid security code"

1017

"validCardExpirationDate"

Checks if the card expiration date is valid.

"is not a valid expiration date"

1015

"validSSN"

Checks if SSN is valid - value doesn't start with 000, 666 or a 9, has nine digits total, and is separated by dashes.

"is not a valid ssn"

1019

"compareValue"

Use it for comparing one field value with another VGS Collect.js field value. It might be used if you want a user to type the SSN or password twice to ensure there is no typo.

"comparison failed"

1020

"postal_code/<ISO_countries_list>"

Available for type='text' only. Checks if the value matches at least one postal code pattern for the countries specified in the list. List of countries and correct ISO codes you can find here.

"is not a valid US zip/postal code"

1018

regExp

Specify any RegExp to validate your field value.

"the value doesn't match a pattern"

1010

Accessibility
Property
Type
Description

ariaLabel

string

Is used to define a string that labels the current element. By default, each field has its own aria-label value, but you can redefine it and specify the purpose for better accessibility.

iframeTitle

string

Contains text representing advisory information related to the iframe it belongs to.

cardIconAltText

boolean | object

Card icon alt attribute value.

// Remove alt attribute
cardIconAltText: false,
// Overwrite alt text
cardIconAltText: {
  cardPlaceholder: '<custom alt text>',
  visa: '<custom alt text>',
  mastercard:  '<custom alt text>',
  ...
}

disabled

boolean

Specifies that the input field is disabled.

hideValue

boolean

Use it if you would like to hide entered value to prevent shoulder surfing attacks.

form.cardNumberField()


Creates a card number field with predefined attributes and default validations.

form.cardNumberField(selector, properties)

Example:

form.cardNumberField('#card-number');

Parameters:

Argument
Type
Description

selector (required)

string

CSS selector that points to the DOM element where the iframe will be added.

properties

object

Optional field configuration object. You can override the default placeholder, add custom validations, styling, or other options supported by form.field() .

form.cardExpirationDateField()


Creates a card expiration date field with predefined attributes, serializers, and validations. Sets type: 'card-expiration-date', name: 'exp-date', includes default placeholder 'mm / yyyy', adds serializers to split month/year, and validates using 'required' and 'validCardExpirationDate'.

form.cardExpirationDateField(selector, properties)

Example:

form.cardExpirationDateField('#expiration-date');

Parameters:

Argument
Type
Description

selector (required)

string

CSS selector that points to the DOM element where the iframe will be added.

properties

object

Optional field configuration object. You can override the default placeholder, add custom validations, styling, or other options supported by form.field() .

form.cardCVCField()


Creates a CVC/CVV field with predefined attributes and validations. Uses type: 'card-security-code', name: 'cvc', sets the placeholder to 'CVC/CVV', and includes 'required' 'validCardSecurityCode' validations by default.

form.cardCVCField(selector, properties)

Example:

form.cardCVCField('#cvc');

Parameters:

Argument
Type
Description

selector (required)

string

CSS selector that points to the DOM element where the iframe will be added.

properties

object

Optional field configuration object. You can override the default placeholder, add custom validations, styling, or other options supported by form.field() .

form.cardholderNameField()


Creates a text field for cardholder name with predefined attributes. Sets type: 'text', name: 'cardholder', and placeholder 'Cardholder Name'. No default validations are enforced.

form.cardholderNameField(selector, properties)

Example:

form.cardholderNameField('#cardholder');

Parameters:

Argument
Type
Description

selector (required)

string

CSS selector that points to the DOM element where the iframe will be added.

properties

object

Optional field configuration object. You can override the default placeholder, add custom validations, styling, or other options supported by form.field() .

form.useCname()


Specify your CNAME. If specified, the data will go through the cname instead of the vault URL. Please make sure you have activated CNAME on the Dashboard.

form.useCname(cname)

Example:

const form = VGSCollect.create('tnt12345678', 'sandbox', (state) => {})
              .useCname('my-cname.com');

Parameters:

Argument
Type
Description

cname (required)

string

CNAME domain (e.g. my-custom-hostname.com)

form.setRouteId()

Route HTTP request to a specific Inbound Route.

form.setRouteId(routeId)

Example:

const form = VGSCollect.create('tnt12345678', 'sandbox', (state) => {})
              .setRouteId('38829k18-dlo1-4kl6-9f7d-a45e34b572f97');

Parameters:

Argument
Type
Description

routeID (required)

string

Inbound Route ID.

form.on()

Listen to events that are related to the whole form state.

form.on(event, callback)

Example:

type EnterPressData = {
  name: string;
}

const form = VGSCollect.create('tnt12345678','sandbox', function () {})

form.on('enterPress', (info: EnterPressData) => {
    console.log(info.name);
    submitForm();
});

Parameters:

Argument
Type
Description

event (required)

string

Event type:

  • enterPresss . If you use an HTML form with a submit event listener, pressing the Enter The key inside a text field will trigger the submit event. This will not work automatically with VGS Collect.js fields because these fields are rendered inside an iframe, and browsers do not treat them as part of the form.

callback

(info) ⇒ {}

A function to execute each time the event is triggered. The information contains the field name from where submit action was triggered.

form.off()

Unsubscribe from the form event listeners.

form.off(event, callback)

Example:

const form = VGSCollect.create('tnt12345678','sandbox', function () {})

form.off('enterPress', () => {});

Parameters:

Argument
Type
Description

event (required)

string

Event type:

  • enterPresss . If you use an HTML form with a submit event listener, pressing the Enter The key inside a text field will trigger the submit event. This will not work automatically with VGS Collect.js fields because these fields are rendered inside an iframe, and browsers do not treat them as part of the form.

callback

() ⇒ {}

A function to execute each time the event is triggered.

form.unmount()

Unmount the VGS Collect.js form from the DOM.

form.unmount()

Example:

form.unmount();

form.reset()

Reset the form values.

form.reset()

Example:

form.reset();

form.submit()

Send a request to your server through our Inbound proxy.

form.submit(path, options, responseCallback, validationCallback)

Example:

form.submit('/', {
  data: {
    customerEmail: '[email protected]',
  },
  headers: {
    'x-application': 'MyApplication 2.8.3',
  },
  }, function(status, response) {
    console.log("Response has been received", status, response);
  }, function(errors) {
      // errors object:
      //{
      //  <invalid field name>: {
      //    <field state>
      //  },
      //}
  }
);

Parameters:

Argument
Type
Description

path (required)

string

The upstream server endpoint where the data will be submitted to.

options

object

HTTP request additional configuration.

responseCallback

function

The callback function that returns request status and response data.

validationCallback

function

Provides information about invalid fields if any.

Options
Property
Type
Description

data

object | function

Additional data you want to pass along with VGS Collect.js field values. To merge form values with an existing payload structure you can use data as a callback function. It receives an object where keys are all available field names, once the form is submitted Collect.js will securely replace placeholders with actual values.

method

string

HTTP method.

serialization

json | formData

Data serialization type.

headers

object

HTTP headers to be added to the request.

withCredentials

boolean

Indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers, or TLS client certificates. false by default.

form.createCard()

On the form submit HTTP request from the Collect form goes to the CMP API POST /cards endpoint.

form.createCard(options,responseCallback, validationCallback)

Example:

form.createCard({
  auth: "<jwt>",
  data: {
    cardholder: {
      name: "test",
      address: {
        address1: "123 Main St",
        address2: "Suite 456",
        address3: "Line 3",
        address4: "Line 4",
        city: document.getElementById("city_input").value,
        region: "CA",
        postal_code: "12345",
        country: "USA",
      },
    },
  },
}, function(status, response) {
  console.log("Response has been received", status, response);
}, function(errors) {});

Parameters:

Argument
Type
Description

options (required)

object

HTTP request additional configuration.

responseCallback

function

The callback function that returns request status and response data.

validationCallback

function

Provides information about invalid fields if any.

Options
Property
Type
Description

auth(required)

string

Authentication Bearer token.

data

string

Additional data that can be passed to extend the request payload.

form.createAliases()

On the form submit HTTP request from the Collect form goes to the Vault API v2 endpoint. The request payload is preconfigured and no additional data can be sent.

form.createAliases(options, responseCallback, validationCallback)

Example:

form.createAliases({ access_token: Bearer <jwt_token> }, function(status, response) {
  console.log("Response has been received", status, response);
, function(errors) {});

Parameters:

Argument
Type
Description

options (required)

object

HTTP request additional configuration.

responseCallback

function

The callback function that returns request status and response data.

validationCallback

function

Provides information about invalid fields if any.

Options
Property
Type
Description

access_token(required)

string

Authentication Bearer token.

field.on()

Subscribe to events related to the specific form field.

field.on(event, callback)

Example:

type VGSFocusEventData = {
  type: string;
  timeStamp: number;
  isTrusted: boolean;
};

field.on('focus', (event: VGSFocusEventData) => { console.log(event) });
field.on('blur', (event: VGSFocusEventData) => { console.log(event) });

type VGSKeyboardEventData = {
  type: string;
  timeStamp: number;
  isTrusted: boolean;
  key: string | null;
  keyCode: number | null;
  which: number | null;
  metaKey: boolean;
  ctrlKey: boolean;
  keyIndex: number;
  valueHidden: boolean;
};

field.on('keyup', (event: VGSKeyboardEventData) => { console.log(event) });
field.on('keydown', (event: VGSKeyboardEventData) => { console.log(event) });
field.on('keypress', (event: VGSKeyboardEventData) => { console.log(event) });
field.on('update', (fieldState) => { console.log(fieldState) });
field.on('delete', () => {});

Parameters:

Argument
Type
Description

event (required)

string

Field events.

callback

() ⇒ {}

A function to execute each time the event is triggered.

Events
Property
Type
Description

focus

string

An input element inside the iframe gains focus.

blur

string

An input element inside the iframe is losing focus.

update

string

Field state has been changed.

delete

string

The field was removed from the form.

keyup

string

Fired when a key is released.

keydown

string

Fired when a key is pressed.

keypress

string

Fired when a key that produces a character value is pressed down.

field.off()

Unsubscribe from events related to the specific form field.

field.off(event, callback)

Example:

type VGSFocusEventData = {
  type: string;
  timeStamp: number;
  isTrusted: boolean;
};

field.off('focus', (event: VGSFocusEventData) => { console.log(event) });
field.off('blur', (event: VGSFocusEventData) => { console.log(event) });

type VGSKeyboardEventData = {
  type: string;
  timeStamp: number;
  isTrusted: boolean;
  key: string | null;
  keyCode: number | null;
  which: number | null;
  metaKey: boolean;
  ctrlKey: boolean;
  keyIndex: number;
  valueHidden: boolean;
};

field.off('keyup', (event: VGSKeyboardEventData) => { console.log(event) });
field.off('keydown', (event: VGSKeyboardEventData) => { console.log(event) });
field.off('keypress', (event: VGSKeyboardEventData) => { console.log(event) });
field.off('update', (fieldState) => { console.log(fieldState) });
field.off('delete', () => {});

Parameters:

Argument
Type
Description

event (required)

string

Field events.

callback

() ⇒ {}

A function to execute each time the event is triggered.

Events
Property
Type
Description

focus

string

An input element inside the iframe gains focus.

blur

string

An input element inside the iframe is losing focus.

update

string

Field state has been changed.

delete

string

The field was removed from the form.

keyup

string

Fired when a key is released.

keydown

string

Fired when a key is pressed.

keypress

string

Fired when a key that produces a character value is pressed down.

field.update()

Dynamic update of the form field properties.

field.update(properties)

Example:

const cvvField = form.field("#cc-cvv", {
  type: 'card-security-code',
  name: 'cvc',
  hideValue: true
});

onCvvVisibilityChange((isVisible) => {
  cvvField.update({
    hideValue: !isVisible
  })
});

Parameters:

Argument
Type
Description

properties (required)

object

List of properties that can be updated: validations placeholder ariaLabel options css hideValue autoComplete disabled readOnly showCardIcon

field.reset()

Reset the form field value.

field.reset()

Example:

const name = form.field('#space-for-my-field', {
  type: 'text',
  name: 'holder_name',
  validations: ['required'],
});
name.reset();

field.delete()

Remove the iframe from the DOM and the form state.

field.delete()

Example:

const zipCode = form.field("#zip-code", { ... });
if (fieldIsNoLongerNeeded) {
  zipCode.delete();
}

field.mask()

Constrain user input. This method is available for those types of Collect fields: text, textarea, password, zip-code.

field.mask(mask, maskChar, formatChar)

Example:

field.mask('999-99-9999', '*');
field.mask('XXXXX', null, {'X': '[0-9]'});

Parameters:

Argument
Type
Description

mask

string

Mask string. Default format characters are: 9: [0-9], a: [A-Za-z], *: [A-Za-z0-9].

maskChar

string

Character to cover unfilled parts of the mask. By default - null.

formatChar

object

Defines format characters with characters as keys and corresponding RegExp strings as a value.

field.replacePattern()

The method returns a new string with some or all matches of a pattern replaced by a replacement. It will modify the value as the user types in the input field. This method is available for those types of fields: text, textarea, password, zip-code.

field.replacePattern(regExpString, newSubStr)

Example:

field.replacePattern('/[^a-zA-Z\s]+/g');
field.replacePattern('/[^\d]+/g');

Parameters:

Argument
Type
Description

regExpString

string

A RegExp object or literal. The match or matches are replaced with a new substring.

newSubStr

string

The string that replaces the substring specified by the regExp. By default - empty string.

Last updated