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.3.0/vgs-collect.js"></script>npm i @vgs/collect-js
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:
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:
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
}messagestringA short, human-readable error message (e.g.,"is required").detailsobjectAdditional metadata about the error. Contents vary depending on the validation rule.descriptionstringA descriptive error string. Often duplicatesmessagebut may provide extended context.codenumberA machine-readable error code identifying the type of validation failure (e.g.,1001for “required”).
VGSCollect.subscribe()
Subscribe to the VGS Collect.js form instance events.
VGSCollect.subscribe(event, callback)
Example:
Parameters:
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:
Parameters:
selector (required)
string
CSS selector that points to the DOM element where the iframe will be added.
properties (required)
object
Field properties.
General Properties
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:
serializers
object[]
Change the format of the value being sent to the server.
Card Number Properties
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.
cardPlaceholdercard 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:
Card Security Code Properties
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.
cardPlaceholdercard icon for empty and undefined card brand states.
cvvFrontcard icon for the front (Amex) CVV.
cvvBackcard icon for the back CVV.
Card Expiration Date Properties
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
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
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.
Validation
"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
"validABARoutingNumber"
Validates a U.S. ABA routing number. A valid routing number must:
Contain exactly 9 digits
Pass the official ABA checksum formula, which verifies that the number is structurally valid and not mistyped
Include only numeric characters
"is not a valid ABA routing number"
1022
"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
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.
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:
Parameters:
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:
Parameters:
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:
Parameters:
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:
Parameters:
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:
Parameters:
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:
Parameters:
routeID (required)
string
Inbound Route ID.
form.on()
Listen to events that are related to the whole form state.
form.on(event, callback)
Example:
Parameters:
event (required)
string
Event type:
enterPresss. If you use an HTMLformwith asubmitevent listener, pressing theEnterThe key inside a text field will trigger thesubmitevent. 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:
Parameters:
event (required)
string
Event type:
enterPresss. If you use an HTMLformwith asubmitevent listener, pressing theEnterThe key inside a text field will trigger thesubmitevent. 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.reset()
Reset the form values.
form.reset()
Example:
form.submit()
Send a request to your server through our Inbound proxy.
form.submit(path, options, responseCallback, validationCallback)
Example:
Parameters:
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
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:
Parameters:
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
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:
Parameters:
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.
field.on()
Subscribe to events related to the specific form field.
field.on(event, callback)
Example:
Parameters:
event (required)
string
Field events.
callback
() ⇒ {}
A function to execute each time the event is triggered.
Events
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:
Parameters:
event (required)
string
Field events.
callback
() ⇒ {}
A function to execute each time the event is triggered.
Events
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:
Parameters:
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:
field.delete()
Remove the iframe from the DOM and the form state.
field.delete()
Example:
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:
Parameters:
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:
Parameters:
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

