Element Methods
Once you have created and mounted an element, you can invoke the following methods to interact with it. These methods provide a consistent API for manipulating elements regardless of which component type you're using.
Core Methods
All Elements support these fundamental interaction methods:
Method | Return Type | Description |
---|---|---|
clear() | void | Clears the element input(s) value |
focus() | void | Focuses on the element input |
blur() | void | Blurs (unfocuses) the element input |
validate() | void | Triggers validation on the element programmatically |
setValue(tokenData) | void | Sets the element's value from a token reference (for displaying tokenized data) |
Component-Specific Methods
Some element types provide additional methods for specialized functionality:
Method | Return Type | Eligible Elements | Description |
---|---|---|---|
month() | number | cardExpirationDate | Returns the month value of the input date (1-12) |
year() | number | cardExpirationDate | Returns the four-digit year value of the input date |
format(formatString) | string | cardExpirationDate | Returns the expiration date formatted according to the specified pattern |
setValueRef(element) | void | text, cardNumber, cardExpirationDate, cardElement, cardVerificationCode | Sets the element's value to match the value of another element |
Method Examples
Basic Element Manipulation
- Web Elements
- React Elements
// Create and mount the element
const textElement = bt.createElement('text', {
targetId: 'my-input'
});
await textElement.mount('#container');
// Clear the value
textElement.clear();
// Focus the element
textElement.focus();
// Later, blur (unfocus) the element
textElement.blur();
// Trigger validation programmatically
textElement.validate();
import { useRef } from 'react';
import { TextElement } from '@basis-theory/react-elements';
function MyComponent() {
const textRef = useRef();
const handleReset = () => {
// Access the element methods via ref
textRef.current.clear();
textRef.current.focus();
};
const handleValidate = () => {
// Trigger validation programmatically
textRef.current.validate();
};
return (
<>
<TextElement id="my-input" ref={textRef} />
<button onClick={handleReset}>Reset</button>
<button onClick={handleValidate}>Validate</button>
</>
);
}
Programmatic Validation
The validate()
method allows you to trigger validation on any element programmatically. This is useful when you want to validate user input at specific times, such as when a form is submitted or when certain conditions are met.
- Web Elements
- React Elements
// Create a text element with validation rules
const textElement = bt.createElement('text', {
targetId: 'ssn-input',
validateOnChange: true,
validation: new RegExp('^\\d{3} \\d{2} \\d{4}$'), // SSN format: 123 45 6789
});
await textElement.mount('#ssn-container');
// Listen for validation changes
textElement.on('change', function (event) {
console.log('Valid:', event.valid);
console.log('Errors:', event.errors);
});
// Trigger validation manually (e.g., on form submission)
function validateForm() {
textElement.validate(); // This will trigger validation and fire change event
// Check validation state
if (textElement.metadata.valid) {
console.log('Element is valid');
} else {
console.log('Element has validation errors:', textElement.metadata.errors);
}
}
import { useRef, useState } from 'react';
import { TextElement } from '@basis-theory/react-elements';
function ValidationExample() {
const textRef = useRef();
const [validationState, setValidationState] = useState({
valid: false,
errors: []
});
const handleChange = (event) => {
setValidationState({
valid: event.valid,
errors: event.errors
});
};
const handleValidate = () => {
// Trigger validation programmatically
textRef.current.validate();
};
const handleSubmit = () => {
// Validate before submission
textRef.current.validate();
if (validationState.valid) {
// Proceed with form submission
console.log('Form is valid, submitting...');
} else {
console.log('Please fix validation errors');
}
};
return (
<>
<TextElement
id="ssn-input"
ref={textRef}
validateOnChange={true}
validation={/^\d{3} \d{2} \d{4}$/} // SSN format
onChange={handleChange}
/>
<div>
Status: {validationState.valid ? 'Valid' : 'Invalid'}
{validationState.errors.length > 0 && (
<div>Errors: {validationState.errors.map(e => e.type).join(', ')}</div>
)}
</div>
<button onClick={handleValidate}>Validate</button>
<button onClick={handleSubmit}>Submit</button>
</>
);
}
validate()
method will trigger validation based on the element's configured validation rules (such as validation
regex patterns for text elements or built-in validation for card elements). The validation results will be available through the element's metadata
property and will also trigger a change
event.Card Expiration Date Methods
The cardExpirationDate
element provides specialized methods for working with date values:
Date Part Extraction
// Create and mount the expiration date element
const expirationElement = bt.createElement('cardExpirationDate', {
targetId: 'expiration'
});
await expirationElement.mount('#expiration-container');
// User enters "04/26" in the field
// Get individual date parts
const month = expirationElement.month(); // 4 (as number)
const year = expirationElement.year(); // 2026 (as number)
// Use these values when tokenizing
const token = await bt.tokens.create({
type: 'card',
data: {
number: cardNumberElement,
expiration_month: expirationElement.month(), // 4
expiration_year: expirationElement.year(), // 2026
cvc: cvcElement
}
});
Date Formatting
The format()
method implements Luxon's toFormat method, supporting all of Luxon's formatting tokens:
// Create the expiration date element
const cardExpirationDateElement = bt.createElement("cardExpirationDate", {
targetId: "expirationDate",
value: "04/25", // April 2025
});
// Format the date in different ways
const formats = {
yearMonth: cardExpirationDateElement.format("yyyy-MM"), // "2025-04"
monthOnly: cardExpirationDateElement.format("MM"), // "04"
monthNumeric: cardExpirationDateElement.format("M"), // "4"
fullDate: cardExpirationDateElement.format("MM/yyyy"), // "04/2025"
shortYear: cardExpirationDateElement.format("yy") // "25"
};
Element Value Synchronization
The setValueRef()
method allows you to synchronize one element's value with another, which is useful for creating "read-only" displays of sensitive data:
// Create the source element (active input)
const cardExpirationDateElement = bt.createElement("cardExpirationDate", {
targetId: "expirationDate",
value: "04/25",
});
// Create a read-only element to display the same value
const cardExpirationDateElementReadOnly = bt.createElement("cardExpirationDate", {
targetId: "expirationDateReadOnly",
readOnly: true // Important: Make the target element read-only
});
// Link the elements - target will update whenever source changes
cardExpirationDateElementReadOnly.setValueRef(cardExpirationDateElement);
setValueRef
to keep an element in sync with another, always make the target element readOnly
. This prevents conflicting inputs and ensures a consistent user experience.Setting Values from Tokens
The setValue()
method allows you to populate an element with previously tokenized data:
// Create an element to display tokenized data
const cardElement = bt.createElement('card', {
targetId: 'display-card',
readOnly: true
});
await cardElement.mount('#display-container');
// Retrieve a token and populate the element
const token = await bt.tokens.retrieve('ca9f3fd7-3906-4087-83aa-9a6129221297', {
apiKey: sessionKey
});
// Set the token data into the element
cardElement.setValue(token.data);
setValue
method only works with data retrieved through Basis Theory services. You cannot pass arbitrary values into this method due to the security boundary between your application and the Element's secure iframe.Related Topics
- Element Lifecycle - Learn about element creation, mounting, and updating
- Component Reference - View all available Element components
- Events - Handle element events like change, focus, blur
- Services - Tokenize data and integrate with third parties