Class CreditCardField

All Implemented Interfaces:
Animation, Editable, ActionSource, StyleListener, TextHolder

public class CreditCardField extends TextField

A text field for a payment card number. It groups the digits as the brand prints them (4-6-5 for American Express, fours otherwise), detects the brand from the leading digits and checks the number with the Luhn checksum.

CreditCardField card = new CreditCardField();
Button pay = new Button("Pay");
card.addDataChangedListener((type, index) -> pay.setEnabled(card.isValidNumber()));

The field only formats and validates. It never stores or sends the number; hand getNumber() to the payment provider's own API, preferably one that tokenizes it.

  • Field Details

  • Constructor Details

    • CreditCardField

      public CreditCardField()
      A card number field.
  • Method Details

    • getBrand

      public String getBrand()

      The brand the number belongs to.

      Returns

      one of the brand constants, #UNKNOWN while the leading digits are not enough

    • getNumber

      public String getNumber()

      The digits typed, without the grouping spaces.

      Returns

      the card number

    • isValidNumber

      public boolean isValidNumber()

      Whether the number has a valid length for its brand and passes the Luhn check.

      Returns

      true for a number worth sending to the payment provider

    • luhn

      public static boolean luhn(String digits)

      The Luhn (mod 10) checksum card numbers carry in their last digit.

      Parameters
      • digits: the number, digits only
      Returns

      true when the checksum holds

    • detectBrand

      public static String detectBrand(String digits)

      The brand the leading digits of a number belong to.

      Parameters
      • digits: the number or its first digits
      Returns

      one of the brand constants