UI Components

UI Components

VGSTextField

An object that displays an editable text area in your interface.

Declaration

class VGSTextField: UIView

VGSTextField UI attributes

VGSTextField have similar attributes to native iOS UITextField attributes. To check full list of available attributes check VGSCollectSDK Reference Docs

VGSTextField Functional attributes

The VGSTextField class provide built-in support for input text validation and formatting. Each VGSTextField should be configured with VGSConfiguration or one of available tokenization configurations.

Attribute

Description

configuration

VGSConfiguration instance, specifies textfield required configuration

delegate

VGSTextFieldDelegate object that will handle text field editing process

state

read-only State instance, represent textfield's current parameters as isValid, isEmpty, etc.

To use all the power of VGSTextField you can track VGSTextField.state object and implement VGSTextFieldDelegate methods.

VGSTextField Accessibility attributes

Attribute

Description

textFieldAccessibilityLabel

String instance, localized string to identify the accessibility text field

textFieldAccessibilityHint

String instance, brief description of the result of performing an action on the accessibility text field

textFieldIsAccessibilityElement

Boolean value, determinates if the text field should be exposed as an accesibility element

VGSTextFieldDelegate

VGSTextFieldDelegate include functionality similar to native UITextFieldDelegate.

Declaration

protocol VGSTextFieldDelegate

Managing VGSTextField Editing process

/// VGSTextField did become first responder
optional func vgsTextFieldDidBeginEditing(_ textfield: VGSTextField)

/// VGSTextField's input changed
optional func vgsTextFieldDidChange(_ textField: VGSTextField)

/// VGSTextField did resign first responder
optional func vgsTextFieldDidEndEditing(_ textfield: VGSTextField)

/// VGSTextField did resign first responder on Return button pressed
optional func vgsTextFieldDidEndEditingOnReturn(_ textfield: VGSTextField)

Code example

class ViewController {

  var expCardDateField = VGSTextField()
  var cardNumberField = VGSCardTextField()

  // ...

  /// Set VGSTextFieldDelegate to handle editing events
  expCardDateField.delegate = self
  cardNumberField.delegate = self

  // ...
}

/// Handle VGSTextFieldDelegate methods
extension ViewController: VGSTextFieldDelegate {

  /// VGSTextField did start editing.
  func vgsTextFieldDidBeginEditing(_ textField: VGSTextField) {
    print("\(textField.state.fieldName) did start editing")
    textField.borderColor = .gray
  }

  /// VGSTextField was edited.
  func vgsTextFieldDidChange(_ textField: VGSTextField) {
     print("\(textField.state.fieldName) did changed. Input characters count: \(textField.state.inputLength)")
  }

  /// VGSTextField did resign first responder.
  func vgsTextFieldDidEndEditing(_ textField: VGSTextField) {
    if !textField.state.isValid {
      textField.borderColor = .red
    }
    print("\(textField.state.fieldName) did end editing with state: \(textField.state.description)")
  }

  /// VGSTextField did resign first responder on Return button pressed.
  func vgsTextFieldDidEndEditingOnReturn(_ textField: VGSTextField) {
    /// Switch to next field programatically
    if textField == cardNumberField {
      expCardDateField.becomeFirstResponder()
    }
  }
}

VGSTextField UIResponder methods

/// Returns a Boolean value indicating whether this object is the first responder
var isFirstResponder: Bool

/// Asks UIKit to make this object the first responder
@discardableResult func becomeFirstResponder() -> Bool

/// Asks UIKit to resign this object as first responder
@discardableResult func resignFirstResponder() -> Bool

Compare fields values

You have an option to compare two VGSTextFields. The result will be a Boolean value that represents whether the raw text in two textFelds is equal. All dividers and formatPatterns will be ignored in this function.

Code example

let textField1 = VGSTextField()
let config1 = VGSConfiguration(collector: collector, fieldName: "field1")
textField1.configuration = config1

let textField2 = VGSTextField()
let config2 = VGSConfiguration(collector: collector, fieldName: "field2")
textField2.configuration = config2

/// Check if raw value in two VGSTextField is equal
let isContentEqual = textField1.isContentEqual(textField2)

VGSExpDateTextField

An object that displays an editable text area, for use instead of a VGSTextField with FieldType.expDate when need to advanced expiration date options.

Declaration

class VGSExpDateTextField: VGSTextField

Overview

VGSExpDateTextField inherits same functionality as default VGSTextField. In addition, VGSExpDateTextField provides an option to use date picker as input source instead of keyboard. Input source can be specified in VGSExpDateConfiguration.

Setting date visual format with picker view


/// UIPickerView Month Label format
var monthPickerFormat: MonthFormat

/// UIPickerView Year Label format
var yearPickerFormat: YearFormat

• The date format displayed in the picker doesn't have impact on date format displayed in the field. SDK will automatically convert selected date when setting it into the field, based on the field formatPattern. • Date picker have limited valid expiration date range. Basicaly, it allows to set any date in future from current month plus 20 years. • If you need to collect date with long year format(MM/YYYY) you should update field .formatPattern and change default VGSValidationRuleCardExpirationDate rule in filed validation rules.

Code example

var expCardDate = VGSExpDateTextField()

let expDateConfiguration = VGSExpDateConfiguration(collector: vgsCollect, fieldName: "card_expirationDate")
expDateConfiguration.type = .expDate

expCardDate.configuration = expDateConfiguration
expCardDate.placeholder = "MM/YY"

/// Set input source if needed. Default is `VGSTextFieldInputSource.datePicker`
expDateConfiguration.inputSource = .datePicker

/// Change default date format in picker
/// Set month picker date format as long symbols: e.g.:`January`
expCardDate.monthPickerFormat = .longSymbols
/// Set year picker date format as long year: e.g.:`2021`
expCardDate.yearPickerFormat = .long

/// Output format will be same as field formatPattern:
/// "##/##" - "01/21"
/// OR
/// "##/####" - "01/2021"

VGSDateTextField

An object that displays an editable text area, for use instead of a VGSTextField with FieldType.date when need to advanced date options.

Declaration

class VGSDateTextField: VGSTextField

Overview

VGSDateTextField inherits same functionality as default VGSTextField. In addition, it provides an option to validate the date is in a specific range. It also allows to use date picker as input source instead of keyboard. Input source and date range can be specified in VGSDateConfiguration.

Setting month visual format with picker view


/// UIPickerView Month Label format
var monthPickerFormat: MonthFormat

• The date format displayed in the picker doesn't have impact on date format displayed in the field. SDK will automatically convert selected date when setting it into the field, based on the field formatPattern. • Date picker will use the datePickerStartDate and datePickerEndDate dates as limited valid range. If they are not supplied, it will use the default range as: - datePickerStartDate: Today minus 100 years. - datePickerEndDate: Today plus 100 years.\

Code example

var dateField = VGSDateTextField()

/// Set start and end dates, this is optional
let startDate = VGSDate(day: 1, month: 1, year: 2010)
let endDate = VGSDate(day: 1, month: 1, year: 2020)
        
/// Date format
let inputDateFormat = VGSDateFormat.mmddyyyy
        
/// Create configuration
let dateFieldConfiguration = VGSDateConfiguration(
  collector: vgsCollect,
  fieldName: "date_field",
  datePickerStartDate: startDate,
  datePickerEndDate: endDate
)
dateFieldConfiguration.inputDateFormat = inputDateFormat
dateFieldConfiguration.outputDateFormat = .yyyymmdd
dateFieldConfiguration.inputSource = .datePicker
dateFieldConfiguration.divider = "-"
dateFieldConfiguration.formatPattern = "##/##/####"
        
/// Setup validation rules, it is important to set the same start date,
/// end date and input date format used in the configuration
dateFieldConfiguration.validationRules = VGSValidationRuleSet(
  rules: [
    VGSValidationRuleDateRange(
      dateFormat: inputDateFormat,
      error: VGSValidationErrorType.date.rawValue,
      start: startDate,
      end: endDate
    )
  ]
)
        
/// Update configuration in the text field
dateField.configuration = dateFieldConfiguration
dateField.placeholder = "MM/DD/YYYY"
dateField.monthPickerFormat = .longSymbols

/// Input format will use the formatPattern to display the date:
/// "01-02-2000" - "01/02/2010"
///
/// Output format will be same as field formatPattern using the divider:
/// "##/##/####" - "2010-02-01"
///
/// If no custom divider is set, output format will use the default divider "/":
/// "##/##/####" - "2010/02/01"

VGSCardTextField

An object that displays an editable text area, for use instead of a VGSTextField when we need to detect and show credit card brand images.

Declaration

class VGSCardTextField: VGSTextField

Overview

VGSCardTextField inherits the same functionality as the default VGSTextField. In addition, it detects the credit card brand while the user is typing data and displays the brand image in a text field. All card brand images are included in the SDK; however, you can still set your custom images.

Setting custom card brand images


/// set card brand icon location inside VGSCardTextField
var cardIconLocation: VGSCardTextField.CardIconLocation

/// set card brand icon size inside VGSCardTextField
var cardIconSize: CGSize

/// set image for specific card type
var cardsIconSource: ((VGSPaymentCard.CardBrand) -> UIImage?)?

Code example

var cardNumberField = VGSCardTextField()
cardNumberField.cardIconLocation = .left
cardNumberField.cardIconSize = CGSize(width: 45, height: 45)

/// Set card brand icons globally
VGSPaymentCards.visa.brandIcon = UIImage(named: "my visa icon")
VGSPaymentCards.unknown.brandIcon = UIImage(named: "my unknown brand icon")

/// OR

/// Set card brand icons for specific textfield
cardNumberField.cardsIconSource = { cardBrand in
    switch cardBrand {
    case .mastercard:
        return UIImage(named: "<custom mastercard icon>")
    case .visa:
        return UIImage(named: "<custom visa icon>")
    default:
        return nil
    }
}

VGSCVCTextField

An object that displays an editable text area, for use instead of a VGSTextField when need to show CVC icons for specific card brands.

Declaration

class VGSCVCTextField: VGSTextField

Overview

VGSCVCTextField inherits same functionality as default VGSTextField. In addition it displays CVC image. CVC image can change dynamically for specific card brand(e.g. CVC image for Amex contains 4 digits). CVC image files are included in the SDK, however you still can set your custom images.

Setting custom CVC images


/// set CVC icon location inside VGSCVCTextField
var cvcIconLocation: VGSCVCTextField.CVCIconLocation

/// set CVC icon size inside VGSCVCTextField
var cvcIconSize: CGSize

/// set CVC image for specific card brand
var cvcIconSource: ((VGSPaymentCard.CardBrand) -> UIImage?)?

Code example

var cvcCardNum = VGSCVCTextField()
cvcCardNum.cvcIconLocation = .right
cvcCardNum.cvcIconSize = CGSize(width: 45, height: 45)

/// Set card brand icons globally
VGSPaymentCards.amex.cvcIcon = UIImage(named: "my CVC icon for Amex")
VGSPaymentCards.unknown.cvcIcon = UIImage(named: "my CVC icon for unknown brand")

/// OR

/// Set card brand icons for specific textfield
cvcCardNum.cvcIconSource = { cardBrand in
    switch cardBrand {
    case .mastercard:
        return UIImage(named: "<custom CVC icon for MasterCard>")
    case .amex:
        return UIImage(named: "<custom CVC icon for Amex>")
    default:
        return nil
    }
}

For more details about available attributes and functionality check VGSCollectSDK Reference docs

Managing Payment Card Brands

By default, VGSCollectSDK supports a certain list of Payment Card Brands. For more accurate card brand detection and card number validation, you can edit default Payment Card Models or add a new Custom Payment Card Model. You can find a full list of default Payment Card Models supported by VGSCollectSDK in VGSPaymentCards class.

Customize Default Payment Card Models

When you need to change existing Payment Card Model attributes, you can do it by editing models in VGSPaymentCards. VGSPaymentCards contains the full list of predefined Payment Card Models and stores your Custom Payment Card Models.

VGSPaymentCards.visa.regex = "^9\\d*$"
VGSPaymentCards.visa.name = "NEW VISA"
VGSPaymentCards.visa.cardNumberLengths = [16]
VGSPaymentCards.visa.formatPattern = "#### #### #### ####"
VGSPaymentCards.visa.brandIcon = UIImage(named: "My new icon")

You don't need to setup Payment Card Models every time you start collecting cards data flow. All the the changes will be available in the App for each VGSCollect instance. It's recommended to edit default Payment Card Models or add Custom Card Models once per App runtime.\

Didn't Find Supported Card Brand?

If you didn't find supported Payment Card Models by VGSCollectSDK you have two options: add your custom brand or validate all unknown card brands.

Add Custom Payment Card Models

You can add your own Payment Card Models to VGSPaymentCards.availableCards array.

let customBrandModel = VGSCustomPaymentCardModel(name: "my custom brand",
                                                 regex: "^9\\d*$",
                                                 formatPattern: "#### #### #### #### ###",
                                                 cardNumberLengths: [15, 16, 19],
                                                 cvcLengths: [3],
                                                 checkSumAlgorithm: .luhn,
                                                 brandIcon: UIImage(named: "my custom brand icon"))
VGSPaymentCards.cutomPaymentCardModels = [customBrandModel]

Custom Payment Card Models have priority on Default Payment Card Model. That means if custom card model have same regex as default card model, SDK will recognize card number as your Custom Brand.\

Validate Unknown Card Brands

In case if you want to validate all cards that not supported by VGSCollectSDK or that don't match your Custom Payment Card Models, you still can do it by enabling CardBrand.unknown validation and updating attributes in VGSPaymentCards.unknown object.

/// Edit default unknown card brand attributes
VGSPaymentCards.unknown.cardNumberLengths = Array(15...19)
VGSPaymentCards.unknown.cvcLengths = [3, 4]
VGSPaymentCards.unknown.formatPattern = "#### #### #### #### ###"
VGSPaymentCards.unknown.brandIcon = UIImage(named: "Unknown-card-types-icon")

/// Enable validation unknown card brands in VGSTextField configuration
let cardConfiguration = VGSConfiguration(collector: vgsCollect, fieldName: "card_number")
cardConfiguration.type = .cardNumber

cardConfiguration.validationRules = VGSValidationRuleSet(rules: [
  VGSValidationRulePaymentCard(error: "card_validation_error", validateUnknownCardBrand: true)
])

Set Valid Card Brands

You can choose which card brands you want to support in your Application. To do that, you need to setup VGSPaymentCards.validCardBrands array with CardBrans that should be detected as valid brand. When user enters card number that not related CardBrands from validCardBrands array, SDK will produce validation error. By default, validCardBrands include all your Custom Card Brands & Default Card Brands supported by SDK.

VGSPaymentCards.validCardBrands = [VGSPaymentCards.visaElectron, VGSPaymentCards.visa, customBrand, VGSPaymentCards.masterCard]

• Brands order is important. Order will define what CardBrand will be detected first. • If you need to use Custom Card Brands, you should add them to validCardBrands in accordance with required order. • If you need to edit default CardBrands*, this should be done before adding them into validCardBrands array.

Last updated