Skip to main content

Components

This document describes the available Basis Theory Element components for both JavaScript and React implementations. Each component provides a secure method for collecting sensitive data without exposing it to your application code.

CardElement

A complete payment card input that combines card number, expiration date, and security code fields in a single component.

Card Element

Properties:

PropertyTypeRequiredDescription
id / targetIdstringYesUnique identifier for the element
placeholderobjectNoCustom placeholders for each field: {cardNumber, cardExpirationDate, cardSecurityCode}
styleobjectNoCustom styling for the element (see Style Object)
enableCopybooleanNoEnable copy functionality (Chromium browsers only)
copyIconStylesobjectNoCustomize copy icon appearance
cardBrandsarrayNoLimit accepted card brands

Implementation:

// Create the element
const cardElement = bt.createElement('card', {
targetId: 'my-card',
placeholder: {
cardNumber: 'Card number',
cardExpirationDate: 'MM/YY',
cardSecurityCode: 'CVC'
},
style: {
base: {
color: "#32325d",
fontFamily: "Arial, sans-serif",
fontSize: "16px"
}
}
});

// Mount the element
cardElement.mount('#card-container');

Usage Notes:

  • Best suited for standard payment forms
  • Not recommended for mobile viewports under 400px wide
  • Automatically validates and formats card information

TextElement

A general-purpose input for any sensitive string data.

Text Element

Properties:

PropertyTypeRequiredDescription
id / targetIdstringYesUnique identifier for the element
placeholderstringNoPlaceholder text
maskarrayNoFormat input with regex patterns and static characters
transformregexp or arrayNoTransform input before tokenization
validationregexp or functionNoInput validation rule
validateOnChangebooleanNoValidate while typing vs. on blur
maxLengthnumberNoMaximum input length
passwordbooleanNoDisplay as password input (masked characters)
styleobjectNoCustom styling for the element

Implementation:

// Create the element
const ssnElement = bt.createElement('text', {
targetId: 'ssn-input',
placeholder: 'XXX-XX-XXXX',
mask: [/\d/, /\d/, /\d/, '-', /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/],
transform: /[-]/g, // Remove hyphens when tokenizing
validation: /^\d{3}-\d{2}-\d{4}$/
});

// Mount the element
ssnElement.mount('#ssn-container');

Usage Notes:

  • Suitable for any sensitive data: SSN, bank accounts, addresses, PII, etc.
  • Supports sophisticated input formatting via masks
  • Can transform data before tokenization

Validation

Basic Patterns

Data TypePatternExampleDescription
Alphanumeric^[a-zA-Z0-9]+$abc123Letters and numbers only
Credit Card Number^\\d{4} \\d{4} \\d{4} \\d{4}$1234 5678 9012 3456Credit card with spaces between groups
Currency^\\$\\d{1,3}(,\\d{3})*(\\.[0-9]{2})?$$1,234.56US currency format with optional decimal
Email Address^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$test@example.comStandard email validation
Password^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d@$!%*#?&]{8,}$Pass123!At least 8 chars with at least one letter, one number, and optional special chars
Social Security Number^\\d{3} \\d{2} \\d{4}$123 45 6789SSN with spaces between groups
Tax ID^\\d{5}\\d{0,12}$12345 to 12345678901234567Tax identification numbers (5-17 digits)
US Phone Number^\\(\\d{3}\\) \\d{3}-\\d{4}$(123) 456-7890Standard US phone number format with area code in parentheses
US ZIP Code^\\d{5}(-\\d{4})?$12345 or 12345-6789US ZIP code (5 digits or ZIP+4 format)

Implementation Examples

Adding a US Phone Number Validation

textElement.update({
validation: /^\(\d{3}\) \d{3}-\d{4}$/,
mask: [
'(',
/\d/,
/\d/,
/\d/,
')',
' ',
/\d/,
/\d/,
/\d/,
'-',
/\d/,
/\d/,
/\d/,
/\d/,
],
});
Using SSN Validation
textElement.update({
validation: /^\d{3} \d{2} \d{4}$/,
mask: [/\d/, /\d/, /\d/, ' ', /\d/, /\d/, ' ', /\d/, /\d/, /\d/, /\d/],
});

ZIP Code with Mask

textElement.update({
validation: /^\d{5}(-\d{4})?$/,
// Optional extended ZIP code
mask: [/\d/, /\d/, /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/],
});

Email Address Validation

textElement.update({
validation: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
});

Best Practices

  1. Always use anchors: Include ^ (start) and $ (end) anchors to ensure the entire value is validated, not just a portion.

  2. Match mask and validation: When using both mask and validation, ensure they are compatible with each other.

  3. Consider validation timing: Choose appropriate validation timing based on user experience:

    • validateOnBlur: Validates when the field loses focus
    • validateOnChange: Validates as the user types
  4. Handle optional segments: For patterns with optional segments (like ZIP+4), ensure your mask and validation logic accommodate both formats.

  5. Test thoroughly: Test your regex patterns with various inputs, including edge cases.

Notes on Regex Support

When using regex patterns in Elements:

  • Escape special characters properly
  • Remember that \d matches any digit (0-9)
  • Use quantifiers like ? (zero or one), * (zero or more), + (one or more) appropriately

Input Masking

The TextElement component supports sophisticated input formatting through the mask attribute. This feature enables you to control exactly what users can type and how their input is automatically formatted as they type.

How Masking Works

A mask is defined as an array where each position corresponds to a character position in the input:

  • RegExp objects (e.g., /\d/) specify which characters are allowed at that position
  • String values (e.g., '-') define static characters that are automatically inserted
  • The total length of the array determines the maximum input length

The component will:

  1. Automatically insert static characters as the user types
  2. Only allow input that matches the RegExp patterns
  3. Format the value according to the specified mask

Example: US Phone Number Mask

Consider the following mask for formatting a US phone number:

mask: ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]

This creates the pattern: (XXX) XXX-XXXX

PositionMask ElementEffect
1'('Automatically inserts opening parenthesis
2-4/\d/Only allows digits (0-9)
5')'Automatically inserts closing parenthesis
6' 'Automatically inserts a space
7-9/\d/Only allows digits (0-9)
10'-'Automatically inserts a hyphen
11-14/\d/Only allows digits (0-9)

Complete Implementation Example

// React implementation
<TextElement
id="phone-input"
placeholder="(XXX) XXX-XXXX"
mask={['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]}
onChange={(e) => {
console.log('Is complete:', e.complete);

// Enable submit button only when input is complete
setSubmitEnabled(e.complete);
}}
/>

These improvements maintain the core message while enhancing clarity, adding visual structure, improving the technical explanation, and providing more context for implementation.

Once set, we do not currently allow updating the mask. If you need to update the mask programmatically, don't hesitate to reach out.
For security and performance reasons, we attempt to detect that the regex provided is valid and not susceptible to catastrophic backtracking. If it fails this validation, we will reject the mount promise.

CardNumberElement

A specialized input for card numbers with automatic brand detection.

Card Number Element

Properties:

PropertyTypeRequiredDescription
id / targetIdstringYesUnique identifier for the element
placeholderstringNoPlaceholder text
iconPositionstringNoCard brand icon position: 'left', 'right', 'none'
cardTypesarrayNoSupported card brands (see Card Types)
enableCopybooleanNoEnable copy functionality
copyIconStylesobjectNoCustomize copy icon appearance
styleobjectNoCustom styling for the element

Implementation:

// Create the element
const cardNumberElement = bt.createElement('cardNumber', {
targetId: 'card-number',
placeholder: 'Card number',
iconPosition: 'right'
});

// Mount the element
cardNumberElement.mount('#card-number-container');

// Handle card brand detection
cardNumberElement.on('change', (event) => {
if (event.cardBrand) {
console.log("Detected card brand:", event.cardBrand);
}
});

Usage Notes:

  • Automatically detects and validates card brand
  • Formats number according to card brand specifications
  • Can be used to conditionally render other form fields based on card brand

CardExpirationDateElement

An input specifically for card expiration dates in MM/YY format.

Card Expiration Date Element

Properties:

PropertyTypeRequiredDescription
id / targetIdstringYesUnique identifier for the element
placeholderstringNoPlaceholder text (default: 'MM/YY')
enableCopybooleanNoEnable copy functionality
copyIconStylesobjectNoCustomize copy icon appearance
styleobjectNoCustom styling for the element

Implementation:

// Create the element
const cardExpirationElement = bt.createElement('cardExpirationDate', {
targetId: 'card-expiration',
placeholder: 'MM/YY'
});

// Mount the element
cardExpirationElement.mount('#expiration-container');

// Check completion status
cardExpirationElement.on('change', (event) => {
if (event.complete) {
console.log("Expiration date is complete");
}
});

Usage Notes:

  • Automatically formats input into MM/YY format
  • Validates that date is not in the past
  • Returns complete status for form validation

CardVerificationCodeElement

An input for card security codes (CVV/CVC).

Card Verification Code Element

Properties:

PropertyTypeRequiredDescription
id / targetIdstringYesUnique identifier for the element
placeholderstringNoPlaceholder text (default: 'CVC')
cardBrandstringNoCard brand to determine validation rules
enableCopybooleanNoEnable copy functionality
copyIconStylesobjectNoCustomize copy icon appearance
styleobjectNoCustom styling for the element

Implementation:

// Create the element
const cardCvcElement = bt.createElement('cardVerificationCode', {
targetId: 'card-cvc',
placeholder: 'CVC',
cardBrand: 'visa'
});

// Mount the element
cardCvcElement.mount('#cvc-container');

Usage Notes:

  • Adjusts validation based on card brand (3 digits for most cards, 4 for American Express)
  • Should be updated when card brand changes in CardNumberElement
  • Input is masked for security

Element Methods

Basis Theory Elements provide a rich set of methods for interacting with and manipulating the components. These methods allow you to clear input values, focus elements, extract data, and more.

See the Element Methods documentation for details on how to:

  • Clear, focus, and blur elements
  • Extract values from card expiration dates
  • Format dates with various patterns
  • Set values from tokens
  • Synchronize values between elements

Style Reference

Style Object

Elements can be styled using a style object with the following structure:

{
base: { // Default style
color: '#32325d',
fontFamily: '"Helvetica Neue", sans-serif',
fontSize: '16px',
'::placeholder': {
color: '#aab7c4'
}
},
invalid: { // Style when input is invalid
color: '#fa755a'
},
complete: { // Style when input is complete
color: '#4CAF50'
},
empty: { // Style when input is empty
color: '#c4c4c4'
},
focus: { // Style when input has focus
borderColor: '#80bdff',
boxShadow: '0 0 0 0.2rem rgba(0, 123, 255, 0.25)'
}
}

Style Properties

Elements support the following CSS properties:

  • color
  • fontFamily, fontSize, fontWeight, fontStyle
  • lineHeight, letterSpacing
  • textAlign, textTransform
  • backgroundColor, borderColor, borderWidth, borderRadius
  • padding, margin
  • boxShadow
  • ::placeholder (for placeholder styling)
AttributeRequiredTypeDescription
fontsfalsearrayArray of font URLs
basefalseobjectBase variant style - all other variant styles inherit from this one
completefalseobjectVariant style applied when the element input is complete
emptyfalseobjectVariant style applied when the element input has no value
invalidfalseobjectVariant style applied when the element input has invalid value

You can customize the following pseudo-classes and pseudo-elements inside each variant using a nested object:

  • :hover
  • :focus
  • :disabled
  • ::placeholder
  • ::selection

Here is a complete list of the supported CSS properties:

Variants are resolved per element input. In other words, variant styles will be applied on each element input individually based on their own value.
For security reasons, we currently support only the 1000+ Google Fonts families. If you need a custom font in your Basis Theory Elements, don't hesitate to reach out.

Fonts

Custom Fonts

The fonts attribute accepts an array of custom font urls from Google Fonts and the Basis Theory CDN. The fonts will be loaded asynchronously and will be applied to the elements as soon as they are available.

Fonts located in Basis Theory CDN are:

  • Euclid Circular B
    • https://cdn.basistheory.com/fonts/EuclidCircularB/font-euclidcircularb.css

Included Font Families

We include the following fonts by default and are able to be used without the need to load them from Google Fonts or the Basis Theory CDN:

  • inter
  • conceal (for password elements)

Validation and Tokenization

When using masked inputs:

  • The input is considered incomplete if the user hasn't provided all required characters matching the mask pattern
  • Incomplete inputs will trigger a validation error during tokenization
  • The change event includes a complete property that indicates whether the full mask pattern has been satisfied
  • The displayed value (with formatting) will be used during tokenization unless a transform is applied

Transform

The transform attribute allows you to modify user input before tokenization, enabling you to store data in a standardized format regardless of how it's displayed to users.

How Transform Works

Transform applies a string replacement operation on the input value:

  • You can specify it as a RegExp object (e.g., /[()-]/g)
  • Alternatively, use an array with a RegExp object and an optional replacement string
  • The operation uses JavaScript's String.replace() function internally
  • If no replacement string is provided, an empty string is used (effectively removing matched characters)

Transform vs. Masking

For a US phone number that displays as (123) 456-7890 but should be stored as 1234567890:

var phoneNumberElement = bt.createElement("text", {
targetId: "myPhoneNumberElement",
mask: ["(", /\d/, /\d/, /\d/, ")", /\d/, /\d/, /\d/, "-", /\d/, /\d/, /\d/, /\d/],
transform: /[()-]/g, // Remove parentheses and hyphens
});
Input StageValueDescription
User input(123) 456-7890What the user sees in the input field
After transform1234567890What gets stored after tokenization

The transform operation happens automatically during the tokenization process, ensuring that your stored data is in a clean, consistent format while maintaining a user-friendly display format.

We strip all RegExp object flags defined in the transform and set gu as the flags.
For security and performance reasons, we attempt to detect that the regex provided is valid and not susceptible to catastrophic backtracking. If it fails this validation, we will reject the mount or update promise.

Card Types

Supported card brands with their identifiers:

BrandIdentifierCard Number DigitsCVC Digits
American Expressamerican-express154
Diners Clubdiners-club14, 16, 193
Discoverdiscover16, 193
Eloelo163
Hiperhiper163
HiperCardhipercard163
JCBjcb16-193
Maestromaestro12-193
Mastercardmastercard163
MIRmir16-193
UnionPayunionpay14-193
Visavisa16, 18, 193

Customizing Card Types

You can extend default card brands or create custom ones:

import { VISA, DEFAULT_CARD_TYPES } from "@basis-theory/basis-theory-js/types/elements"

// Create a custom VISA type with additional BIN patterns
const CUSTOM_VISA = {
...VISA,
patterns: [...VISA.patterns, 8456]
};

// Filter out the default VISA type
const customCardTypes = DEFAULT_CARD_TYPES.filter(
({ type }) => type !== 'visa'
);

// Add your custom VISA type
const cardNumberElement = bt.createElement('cardNumber', {
targetId: 'card-number',
cardTypes: [...customCardTypes, CUSTOM_VISA]
});

Complete Options Reference

AttributeTypeUpdatableElementsDescription
aria-labelstringYestext, cardNumber, cardExpirationDate, cardVerificationCodeAccessibility label
autoCompletestringYesAllAutocomplete attribute
cardBrandstringYescardVerificationCodeCard brand for CVC validation
cardTypesarrayNocardNumberSupported card brands
copyIconStylesobjectNocardNumber, cardExpirationDate, cardElement, cardVerificationCodeCopy icon styling
disabledbooleanYesAllDisables the input
enableCopybooleanYescardNumber, cardExpirationDate, cardElement, cardVerificationCodeEnables copy feature
iconPositionstringYescardNumberBrand icon position
inputModestringYesAllInput mode attribute
maskarrayNotextInput formatting mask
maxLengthnumberNotextMaximum input length
passwordbooleanYestextPassword input type
placeholderstring or objectYesAllPlaceholder text
readOnlybooleanYesAllMakes input read-only
styleobjectYesAllCustom styling
transformregexp or arrayYestextTransform before tokenization
validationregexp or functionYestextValidation rule
validateOnChangebooleanYesAllValidation timing

Troubleshooting Component Issues

If you encounter issues with your components, such as formatting problems, validation errors, or elements not displaying properly, refer to our troubleshooting guide.