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

{% tabs %}
{% tab title="CDN" %}

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

{% endtab %}

{% tab title="NPM" %}
npm i @vgs/collect-js
{% endtab %}
{% endtabs %}

## VGSCollect.create() <a href="#api-vgscollectcreate" id="api-vgscollectcreate"></a>

***

Create a VGS Collect form instance.

{% hint style="info" %}
*VGSCollect.create(vaultId, environment, stateCallback)*
{% endhint %}

*Example:*

```javascript
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.  |

<details>

<summary>State Object</summary>

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:**

<table><thead><tr><th width="168.73046875">Property</th><th width="158">Type</th><th width="199.71484375">Description</th><th>Field Type Availability</th></tr></thead><tbody><tr><td><code>isDirty</code></td><td><code>Boolean</code></td><td>Indicates whether the user has modified the field value.</td><td>All</td></tr><tr><td><code>isFocused</code></td><td><code>Boolean</code></td><td>Indicates whether the field is currently focused.</td><td>All</td></tr><tr><td><code>isValid</code></td><td><code>Boolean</code></td><td>Indicates whether the field value passes all validation rules.</td><td>All</td></tr><tr><td><code>isEmpty</code></td><td><code>Boolean</code></td><td><p>Indicates whether the field is empty.</p><p></p></td><td>All</td></tr><tr><td><code>isTouched</code></td><td><code>Boolean</code></td><td>Becomes <code>true</code> after the field has been blurred for the first time.</td><td>All</td></tr><tr><td><code>errorMessages</code></td><td><code>string[]</code></td><td>Contains an array of validation error messages for the field.</td><td>All</td></tr><tr><td><code>errors</code></td><td><code>object[]</code>    <br><br><br>         <br><br><br><br><br></td><td> An array of error objects associated with the field. Each object provides details about a specific validation error. See below section for additional context.</td><td>All </td></tr><tr><td><code>last4</code></td><td><code>string</code></td><td>Contains the last 4 digits of the entered value <strong>only when validation is successfully passed</strong>.</td><td><code>card-number</code>, <code>ssn</code></td></tr><tr><td><code>bin</code></td><td><code>string</code></td><td>Contains the Bank Identification Number (BIN) once the number is valid.</td><td><code>card-number</code></td></tr><tr><td><code>cardType</code></td><td><code>string</code></td><td>Represents the detected card brand (e.g., <code>"visa"</code>, <code>"mastercard"</code>, <code>"amex"</code>). See the list of supported card brands for details.</td><td><code>card-number</code></td></tr><tr><td></td><td></td><td></td><td></td></tr></tbody></table>

**Errors Structure:**

```json
{
  "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”).

</details>

## VGSCollect.subscribe() <a href="#api-vgscollectsubscribe" id="api-vgscollectsubscribe"></a>

***

Subscribe to the VGS Collect.js form instance events.

{% hint style="info" %}
VGSCollect.subscribe(event, callback)
{% endhint %}

*Example:*

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

*Parameters:*

| Argument             | Type    | Description                                                                                                                                                                                                                                  |
| -------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **event** (required) | string  | <p>Event type:</p><ul><li><code>pluginScriptLoad</code> - Triggers after the third-party script (partner's script) has successfully loaded.</li><li><code>fieldLoad</code> - Triggers every time a new field is added to the form.</li></ul> |
| **callback**         | () ⇒ {} | A function to execute each time the event is triggered.                                                                                                                                                                                      |

## form.field() <a href="#api-formfield" id="api-formfield"></a>

***

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

{% hint style="info" %}
form.field(selector, properties)
{% endhint %}

*Example:*

```javascript
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.                                                           |

<details>

<summary>General Properties</summary>

<table><thead><tr><th width="170.5546875">Property</th><th width="172.91796875">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>name</code> (required)</td><td><code>string</code></td><td>Name of the input field. Will be shown in the form state and used as a data key in the request payload.</td></tr><tr><td><code>type</code> (required)</td><td><code>string</code></td><td>Type of the input field. Available field types: <code>card-number</code>, <code>card-security-code</code>, <code>card-expiration-date</code>, <code>ssn</code>, <code>password</code>, <code>text</code>, <code>zip-code</code>, <code>postal-code</code>, <code>file</code>, <code>dropdown</code>, <code>checkbox</code>.</td></tr><tr><td><code>validations</code></td><td><code>string[]</code></td><td>Validations that will be used to calculate the field <code>isValid</code> state.</td></tr><tr><td><code>css</code></td><td><code>object</code></td><td>An object of styles you can apply to the field.</td></tr><tr><td><code>placeholder</code></td><td><code>string</code></td><td>Input placeholder text.</td></tr><tr><td><code>autoComplete</code></td><td><code>string</code></td><td>Allows controlling how the browser should populate a given form field. The most common autocomplete attributes are:<br><code>cc-name</code>, <code>cc-number</code>, <code>cc-csc</code>, <code>cc-exp</code>, <code>name</code>, <code>email</code>, <code>tel</code>, <code>shipping street-address</code>, <code>shipping locality</code>, <code>shipping region</code>, <code>shipping postal-code</code>, <code>shipping country</code></td></tr><tr><td><code>inputMode</code></td><td><code>string</code></td><td>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.</td></tr><tr><td><code>classes</code></td><td><code>object</code></td><td><p>CSS classes that are applied to the container element when the field is in a particular state:</p><pre class="language-javascript"><code class="lang-javascript">{
  '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
}
</code></pre></td></tr><tr><td><code>serializers</code></td><td><code>object[]</code></td><td><p>Change the format of the value being sent to the server.</p><pre class="language-javascript"><code class="lang-javascript">// 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' }}
</code></pre></td></tr></tbody></table>

</details>

<details>

<summary>Card Number Properties</summary>

<table><thead><tr><th width="160.70703125">Property</th><th width="108.20703125">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>showCardIcon</code></td><td><code>boolean</code></td><td>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.</td></tr><tr><td><code>icons</code></td><td><code>object</code></td><td><p>Unfortunately, we cannot use regular HTTP(s) URLs for security reasons. To customise an icon, you need to pass a{" "} <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs">Data URL</a> with an icon. Check the example <a href="https://www.verygoodsecurity.com/docs/vgs-collect/js/customization#override-default-icons">here</a>.</p><ul><li><p><code>cardPlaceholder</code></p><ul><li>card icon for empty and undefined card brand states.</li></ul></li><li><p><code>visa|amex|maestro|...</code></p><ul><li>card icons for particular brands. <a href="https://www.verygoodsecurity.com/docs/vgs-collect/js/customization#card-brand-identification">Full list</a> of types.</li></ul></li></ul></td></tr><tr><td><code>addCardBrands</code></td><td><code>object</code></td><td>Use it if you would like to extend the list of <a href="https://www.verygoodsecurity.com/docs/vgs-collect/js/customization#card-brand-identification">supported card brands</a> or redefine existing card brand pattern. More information you can find <a href="https://www.verygoodsecurity.com/docs/vgs-collect/js/customization#add-custom-card-brands">here</a>.</td></tr><tr><td><code>validCardBrands</code></td><td><code>[]</code></td><td><p></p><p>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 <code>validCardBrands</code> The property to an array contains a list of supported cards in the following format:</p><pre class="language-javascript"><code class="lang-javascript">{
  ...
  validCardBrands: [ { type: 'visa' }, { type: 'mastercard' }],
  ...
}
</code></pre></td></tr></tbody></table>

</details>

<details>

<summary>Card Security Code Properties</summary>

<table><thead><tr><th width="160.70703125">Property</th><th width="108.20703125">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>showCardIcon</code></td><td><code>boolean</code><br><br><br><br></td><td>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.</td></tr><tr><td><code>icons</code></td><td><code>object</code></td><td><p>Unfortunately, we cannot use regular HTTP(s) URLs for security reasons. To customise an icon, you need to pass a{" "} <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs">Data URL</a> with an icon. Check the example <a href="https://www.verygoodsecurity.com/docs/vgs-collect/js/customization#override-default-icons">here</a>.</p><ul><li><p><code>cardPlaceholder</code></p><ul><li>card icon for empty and undefined card brand states.</li></ul></li><li><p><code>cvvFront</code></p><ul><li>card icon for the front (Amex) CVV.</li></ul></li><li><p><code>cvvBack</code></p><ul><li>card icon for the back CVV.</li></ul></li></ul></td></tr></tbody></table>

</details>

<details>

<summary>Card Expiration Date Properties</summary>

<table><thead><tr><th width="160.70703125">Property</th><th width="108.20703125">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>yearLength</code></td><td><code>number</code><br><br><br><br></td><td>Either <code>2</code> or <code>4</code>. Control the length of the year we send to the server. If none is specified by default, we accept both formats.</td></tr><tr><td><code>separator</code></td><td><code>string</code></td><td>Separator to use between the month and year values. Default: <code>" / "</code>.</td></tr></tbody></table>

</details>

<details>

<summary>Text Properties</summary>

<table><thead><tr><th width="160.70703125">Property</th><th width="108.20703125">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>min</code></td><td><code>number</code><br><br><br><br></td><td>Specifies the minimum value for an input element.</td></tr><tr><td><code>max</code></td><td><code>number</code></td><td>Specifies the minimum value for an input element.</td></tr><tr><td><code>maxLength</code></td><td><code>number</code></td><td>Maximum length (number of characters) of value.</td></tr><tr><td><code>step</code></td><td><code>number</code></td><td>Specifies the legal number intervals for an input element.</td></tr></tbody></table>

</details>

<details>

<summary>File Properties</summary>

<table><thead><tr><th width="160.70703125">Property</th><th width="108.20703125">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>multiple</code></td><td><code>boolean</code><br><br><br><br></td><td>If present indicates that the user may choose more than one file.</td></tr><tr><td><code>accept</code></td><td><code>string[]</code></td><td>An array with one or more unique file type specifiers describing file types to allow. By default, set to <code>['images/*', '/pdf']</code>. All available MIME types: <code>image/png</code>, <code>image/apng</code>, <code>image/avif</code>, <code>image/gif</code>, <code>image/jpeg</code>, <code>image/svg+xml</code>, <code>image/svg</code>, <code>image/webp</code>, <code>image/*</code>, <code>.pdf</code>, <code>.csv</code></td></tr><tr><td><code>capture</code></td><td><code>string</code></td><td>String indicated what source to use for capturing image or video data: <code>"user" | "environment"</code>.</td></tr><tr><td><code>maxFileSize</code></td><td><code>number</code></td><td>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: <code>"uploaded file is too large"</code>.</td></tr><tr><td><code>maxFiles</code></td><td><code>number</code></td><td>Indicates maximum allowed file number. If the user uploads more than maxFiles value the form state will receive the following validation error: <code>"maximum n files can be uploaded"</code></td></tr><tr><td><code>serializers</code></td><td><code>obejct[]</code></td><td><p></p><p>Convert file value to base64 format.</p><pre class="language-javascript"><code class="lang-javascript">{ name: 'toBase64' }
</code></pre></td></tr></tbody></table>

</details>

<details>

<summary>Dropdown Properties</summary>

<table><thead><tr><th width="160.70703125">Property</th><th width="108.20703125">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>options</code></td><td><code>object[]</code><br><br><br><br></td><td><p>List of options:</p><pre class="language-js"><code class="lang-js"> options: [
      {value: 'volvo', text: 'Volvo'},
      {value: 'saab', text: 'Saab'},
      {value: 'opel', text: 'Opel'},
      {value: 'audi', text: 'Audi'}
  ],
</code></pre></td></tr></tbody></table>

</details>

<details>

<summary><strong>Validation</strong></summary>

<table><thead><tr><th width="222.29296875">Validation</th><th width="251.921875">Description</th><th width="132.078125">Associated errorMessage</th><th>Error Code</th></tr></thead><tbody><tr><td><code>"required"</code></td><td>Checks if the field is not empty.</td><td>"is required"</td><td>1001</td></tr><tr><td><code>"validCardNumber"</code></td><td>Checks that the number is formatted correctly and passes the <a href="https://en.wikipedia.org/wiki/Luhn_algorithm">Luhn check</a>.</td><td>"is not a valid card number"</td><td>1011</td></tr><tr><td><code>"validCardNumberExtended"</code></td><td>Under the hood extends the cards list with a new <code>unknown</code> card type which becomes valid once the value passes the <strong>Luhn check only</strong> and has <strong>at least 16 symbols</strong>.</td><td>"is not a valid card number"</td><td>1005</td></tr><tr><td><code>"validCardNumberLuhnCheck"</code></td><td>Checks if the card number is passing <strong>Luhn check only.</strong></td><td>"is not a valid card number"</td><td>1004</td></tr><tr><td><code>"validCardSecurityCode"</code></td><td>Checks if the security code is valid based on the card number brand.</td><td>"is not a valid security code"</td><td>1017</td></tr><tr><td><code>"validCardExpirationDate"</code></td><td>Checks if the card expiration date is valid.</td><td>"is not a valid expiration date"</td><td>1015</td></tr><tr><td><code>"validSSN"</code></td><td>Checks if SSN is valid - value doesn't start with 000, 666 or a 9, has nine digits total, and is separated by dashes.</td><td>"is not a valid ssn"</td><td>1019</td></tr><tr><td>"validABARoutingNumber"</td><td><p></p><p>Validates a U.S. ABA routing number.<br>A valid routing number must:</p><ul><li>Contain exactly 9 digits</li><li>Pass the official ABA checksum formula, which verifies that the number is structurally valid and not mistyped</li><li>Include only numeric characters</li></ul></td><td>"is not a valid ABA routing number"</td><td>1022</td></tr><tr><td><code>"compareValue"</code></td><td>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.</td><td>"comparison failed"</td><td>1020</td></tr><tr><td><code>"postal_code/&#x3C;ISO_countries_list>"</code></td><td>Available for <code>type='text'</code> 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 <a href="https://www.verygoodsecurity.com/docs/vgs-collect/js/faq#whats-available-countries-for-postal_code-validation">here</a>.</td><td>"is not a valid US zip/postal code"</td><td>1018</td></tr><tr><td>regExp</td><td>Specify any RegExp to validate your field value.</td><td>"the value doesn't match a pattern"</td><td>1010</td></tr></tbody></table>

</details>

<details>

<summary>Accessibility</summary>

<table><thead><tr><th>Property</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td><code>ariaLabel</code></td><td><code>string</code></td><td>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.</td></tr><tr><td><code>iframeTitle</code></td><td><code>string</code></td><td>Contains text representing advisory information related to the iframe it belongs to.</td></tr><tr><td><code>cardIconAltText</code></td><td><code>boolean | object</code></td><td><p></p><p>Card icon <code>alt</code> attribute value.</p><pre class="language-javascript"><code class="lang-javascript">// Remove alt attribute
cardIconAltText: false,
// Overwrite alt text
cardIconAltText: {
  cardPlaceholder: '&#x3C;custom alt text>',
  visa: '&#x3C;custom alt text>',
  mastercard:  '&#x3C;custom alt text>',
  ...
}
</code></pre></td></tr><tr><td><code>disabled</code></td><td><code>boolean</code></td><td>Specifies that the input field is disabled.</td></tr><tr><td><code>hideValue</code></td><td><code>boolean</code></td><td>Use it if you would like to hide entered value to prevent shoulder surfing attacks.</td></tr></tbody></table>

</details>

## form.cardNumberField() <a href="#api-formcardnumberfield" id="api-formcardnumberfield"></a>

***

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

{% hint style="info" %}
form.cardNumberField(selector, properties)
{% endhint %}

*Example:*

```javascript
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()`](#api-formfield) . |

## form.cardExpirationDateField() <a href="#api-formcardexpirationdatefield" id="api-formcardexpirationdatefield"></a>

***

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'`.

{% hint style="info" %}
form.cardExpirationDateField(selector, properties)
{% endhint %}

*Example:*

```javascript
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()`](#api-formfield) . |

## form.cardCVCField() <a href="#api-formcardcvcfield" id="api-formcardcvcfield"></a>

***

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.

{% hint style="info" %}
form.cardCVCField(selector, properties)
{% endhint %}

*Example:*

```javascript
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()`](#api-formfield) . |

## form.cardholderNameField() <a href="#api-formcardcvcfield" id="api-formcardcvcfield"></a>

***

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

{% hint style="info" %}
form.cardholderNameField(selector, properties)
{% endhint %}

*Example:*

```javascript
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()`](#api-formfield) . |

## form.useCname() <a href="#api-formcardcvcfield" id="api-formcardcvcfield"></a>

***

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.

{% hint style="info" %}
form.useCname(cname)
{% endhint %}

*Example:*

```javascript
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() <a href="#api-formcardcvcfield" id="api-formcardcvcfield"></a>

Route HTTP request to a specific Inbound Route.

{% hint style="info" %}
form.setRouteId(routeId)
{% endhint %}

*Example:*

```javascript
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() <a href="#api-formcardcvcfield" id="api-formcardcvcfield"></a>

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

{% hint style="info" %}
form.on(event, callback)
{% endhint %}

*Example:*

```javascript
type EnterPressData = {
  name: string;
}

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

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

*Parameters:*

<table><thead><tr><th width="138.46875">Argument</th><th width="131.0078125">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong>event</strong> (required)</td><td>string</td><td><p>Event type: </p><ul><li> <code>enterPresss</code> <em>.</em> If you use an HTML <code>form</code> with a <code>submit</code> event listener, pressing the <code>Enter</code> The key inside a text field will trigger the <code>submit</code> 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.</li></ul></td></tr><tr><td><strong>callback</strong></td><td>(info) ⇒ {}</td><td>A function to execute each time the event is triggered. The information contains the field name from where submit action was triggered.</td></tr></tbody></table>

## form.off() <a href="#api-formcardcvcfield" id="api-formcardcvcfield"></a>

Unsubscribe from the form event listeners.

{% hint style="info" %}
form.off(event, callback)
{% endhint %}

*Example:*

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

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

*Parameters:*

<table><thead><tr><th width="138.46875">Argument</th><th width="131.0078125">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong>event</strong> (required)</td><td>string</td><td><p>Event type: </p><ul><li> <code>enterPresss</code> <em>.</em> If you use an HTML <code>form</code> with a <code>submit</code> event listener, pressing the <code>Enter</code> The key inside a text field will trigger the <code>submit</code> 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.</li></ul></td></tr><tr><td><strong>callback</strong></td><td>() ⇒ {}</td><td>A function to execute each time the event is triggered.</td></tr></tbody></table>

## form.unmount() <a href="#api-formcardcvcfield" id="api-formcardcvcfield"></a>

Unmount the VGS Collect.js form from the DOM.

{% hint style="info" %}
form.unmount()
{% endhint %}

*Example:*

```javascript
form.unmount();
```

## form.reset() <a href="#api-formcardcvcfield" id="api-formcardcvcfield"></a>

Reset the form values.

{% hint style="info" %}
form.reset()
{% endhint %}

*Example:*

```javascript
form.reset();
```

## form.submit() <a href="#api-formcardcvcfield" id="api-formcardcvcfield"></a>

Send a request to your server through our Inbound proxy.

{% hint style="info" %}
form.submit(path, options, responseCallback, validationCallback)
{% endhint %}

*Example:*

```javascript
form.submit('/', {
  data: {
    customerEmail: 'joe@example.com',
  },
  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:*

<table><thead><tr><th width="227.375">Argument</th><th width="122.0390625">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong>path</strong> (required)</td><td>string</td><td>The upstream server endpoint where the data will be submitted to.</td></tr><tr><td><strong>options</strong></td><td>object</td><td>HTTP request additional configuration.</td></tr><tr><td><strong>responseCallback</strong></td><td>function</td><td>The callback function that returns request status and response data.</td></tr><tr><td><strong>validationCallback</strong></td><td>function</td><td>Provides information about invalid fields if any.</td></tr></tbody></table>

<details>

<summary>Options</summary>

<table><thead><tr><th width="179.09765625">Property</th><th width="172.453125">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>data</code></td><td>object | function</td><td>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.</td></tr><tr><td><code>method</code></td><td>string</td><td>HTTP method.</td></tr><tr><td><code>serialization</code></td><td><code>json</code> | <code>formData</code></td><td>Data serialization type.</td></tr><tr><td><code>headers</code></td><td>object</td><td>HTTP headers to be added to the request.</td></tr><tr><td><code>withCredentials</code></td><td>boolean</td><td>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.</td></tr></tbody></table>

</details>

## form.createCard() <a href="#api-formcardcvcfield" id="api-formcardcvcfield"></a>

On the form submit HTTP request from the Collect form goes to the [CMP API](https://app.gitbook.com/s/g1pA9re6lCmtaiQAnvjh/developer-resources/api/cards#post-cards) POST `/cards` endpoint.

{% hint style="info" %}
form.createCard(options,responseCallback, validationCallback)
{% endhint %}

*Example:*

```javascript
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:*

<table><thead><tr><th width="227.375">Argument</th><th width="122.0390625">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong>options</strong> (required)</td><td>object</td><td>HTTP request additional configuration.</td></tr><tr><td><strong>responseCallback</strong></td><td>function</td><td>The callback function that returns request status and response data.</td></tr><tr><td><strong>validationCallback</strong></td><td>function</td><td>Provides information about invalid fields if any.</td></tr></tbody></table>

<details>

<summary>Options</summary>

<table><thead><tr><th width="179.09765625">Property</th><th width="172.453125">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>auth</code>(required)</td><td>string</td><td>Authentication Bearer token.</td></tr><tr><td><code>data</code></td><td>string</td><td>Additional data that can be passed to extend the request payload.</td></tr></tbody></table>

</details>

## form.createAliases() <a href="#api-formcardcvcfield" id="api-formcardcvcfield"></a>

On the form submit HTTP request from the Collect form goes to the [Vault API v2](https://docs.verygoodsecurity.com/vault/developer-tools/apis/vault-api) endpoint. The request payload is preconfigured and no additional data can be sent.

{% hint style="info" %}
form.createAliases(options, responseCallback, validationCallback)
{% endhint %}

*Example:*

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

*Parameters:*

<table><thead><tr><th width="227.375">Argument</th><th width="122.0390625">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong>options</strong> (required)</td><td>object</td><td>HTTP request additional configuration.</td></tr><tr><td><strong>responseCallback</strong></td><td>function</td><td>The callback function that returns request status and response data.</td></tr><tr><td><strong>validationCallback</strong></td><td>function</td><td>Provides information about invalid fields if any.</td></tr></tbody></table>

<details>

<summary>Options</summary>

<table><thead><tr><th width="179.09765625">Property</th><th width="172.453125">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>access_token</code>(required)</td><td>string</td><td>Authentication Bearer token.</td></tr></tbody></table>

</details>

## field.on() <a href="#api-formcardcvcfield" id="api-formcardcvcfield"></a>

Subscribe to events related to the specific form field.

{% hint style="info" %}
field.on(event, callback)
{% endhint %}

*Example:*

```javascript
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:*

<table><thead><tr><th width="227.375">Argument</th><th width="122.0390625">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong>event</strong> (required)</td><td>string</td><td>Field events.</td></tr><tr><td><strong>callback</strong></td><td>() ⇒ {}</td><td>A function to execute each time the event is triggered.</td></tr></tbody></table>

<details>

<summary>Events</summary>

<table><thead><tr><th width="179.09765625">Property</th><th width="172.453125">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>focus</code></td><td>string</td><td>An input element inside the iframe gains focus.</td></tr><tr><td><code>blur</code></td><td>string</td><td>An input element inside the iframe is losing focus.</td></tr><tr><td><code>update</code></td><td>string</td><td>Field state has been changed.</td></tr><tr><td><code>delete</code></td><td>string</td><td>The field was removed from the form.</td></tr><tr><td><code>keyup</code></td><td>string</td><td>Fired when a key is released.</td></tr><tr><td><code>keydown</code></td><td>string</td><td>Fired when a key is pressed.</td></tr><tr><td><code>keypress</code></td><td>string</td><td>Fired when a key that produces a character value is pressed down.</td></tr></tbody></table>

</details>

## field.off() <a href="#api-formcardcvcfield" id="api-formcardcvcfield"></a>

Unsubscribe from events related to the specific form field.

{% hint style="info" %}
field.off(event, callback)
{% endhint %}

*Example:*

```javascript
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:*

<table><thead><tr><th width="227.375">Argument</th><th width="122.0390625">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong>event</strong> (required)</td><td>string</td><td>Field events.</td></tr><tr><td><strong>callback</strong></td><td>() ⇒ {}</td><td>A function to execute each time the event is triggered.</td></tr></tbody></table>

<details>

<summary>Events</summary>

<table><thead><tr><th width="179.09765625">Property</th><th width="172.453125">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>focus</code></td><td>string</td><td>An input element inside the iframe gains focus.</td></tr><tr><td><code>blur</code></td><td>string</td><td>An input element inside the iframe is losing focus.</td></tr><tr><td><code>update</code></td><td>string</td><td>Field state has been changed.</td></tr><tr><td><code>delete</code></td><td>string</td><td>The field was removed from the form.</td></tr><tr><td><code>keyup</code></td><td>string</td><td>Fired when a key is released.</td></tr><tr><td><code>keydown</code></td><td>string</td><td>Fired when a key is pressed.</td></tr><tr><td><code>keypress</code></td><td>string</td><td>Fired when a key that produces a character value is pressed down.</td></tr></tbody></table>

</details>

## field.update() <a href="#api-formcardcvcfield" id="api-formcardcvcfield"></a>

Dynamic update of the form field properties.

{% hint style="info" %}
field.update(properties)
{% endhint %}

*Example:*

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

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

*Parameters:*

<table><thead><tr><th width="138.46875">Argument</th><th width="131.0078125">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong>properties</strong> (required)</td><td>object</td><td>List of properties that can be updated: <code>validations</code> <code>placeholder</code> <code>ariaLabel</code> <code>options</code> <code>css</code> <code>hideValue</code> <code>autoComplete</code> <code>disabled</code> <code>readOnly</code> <code>showCardIcon</code></td></tr></tbody></table>

## field.reset() <a href="#api-formcardcvcfield" id="api-formcardcvcfield"></a>

Reset the form field value.

{% hint style="info" %}
field.reset()
{% endhint %}

*Example:*

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

## field.delete() <a href="#api-formcardcvcfield" id="api-formcardcvcfield"></a>

Remove the iframe from the DOM and the form state.

{% hint style="info" %}
field.delete()
{% endhint %}

*Example:*

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

## field.mask() <a href="#api-formcardcvcfield" id="api-formcardcvcfield"></a>

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

{% hint style="info" %}
field.mask(mask, maskChar, formatChar)
{% endhint %}

*Example:*

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

*Parameters:*

<table><thead><tr><th width="138.46875">Argument</th><th width="131.0078125">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong>mask</strong></td><td>string</td><td>Mask string. Default format characters are: <code>9: [0-9]</code>, <code>a: [A-Za-z]</code>, <code>*: [A-Za-z0-9]</code>.</td></tr><tr><td><strong>maskChar</strong></td><td>string</td><td>Character to cover unfilled parts of the mask. By default - null.</td></tr><tr><td><strong>formatChar</strong></td><td>object</td><td>Defines format characters with characters as keys and corresponding RegExp strings as a value.</td></tr></tbody></table>

## field.replacePattern() <a href="#api-formcardcvcfield" id="api-formcardcvcfield"></a>

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

{% hint style="info" %}
field.replacePattern(regExpString, newSubStr)
{% endhint %}

*Example:*

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

*Parameters:*

<table><thead><tr><th width="138.46875">Argument</th><th width="131.0078125">Type</th><th>Description</th></tr></thead><tbody><tr><td><strong>regExpString</strong></td><td>string</td><td>A RegExp object or literal. The match or matches are replaced with a new substring.</td></tr><tr><td><strong>newSubStr</strong></td><td>string</td><td>The string that replaces the substring specified by the regExp. By default - empty string.</td></tr></tbody></table>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.verygoodsecurity.com/vault/developer-tools/vgs-collect/js/reference-documentation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
