creditcard

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

laravel-go-credit-card

CI Go reference docs Go 1.27

Go port of laravel-validation-rules/credit-card: validate card numbers, expiration dates and CVC codes for Laravel for Go.

It aims to produce the same verdicts as the PHP package on Laravel for Go, and is tested against fixtures that PHP itself generates.

Quick start

go get github.com/bowerbird-si/laravel-go-credit-card
package creditcard_test

import (
	"fmt"

	"github.com/bowerbird-si/laravel-go-credit-card"
)

// The README quick start. CI runs this example.
func Example() {
	card, err := creditcard.Parse("4111 0000 0000 0008")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(card.Brand(), card.Brand().Funding(), card)
	// Output: Visa credit Visa card, 16 digits
}

The same code is in example_test.go; CI compiles it, and runs it when it has an // Output: line.

For checkout forms, add the Laravel validation rules and keep both sensitive fields out of session old input. See getting started.

PHP parity

Follows laravel-validation-rules/credit-card 1.12.3 (commit 194f41f4fc7d).

Parity level Abilities Covered Diverged Planned PHP fixtures Last verified
full 42 30 12 0 830 2026-12-04

Every ability is listed in parity.toml, with the tests that cover it or the reason it differs.

Differences from PHP

The specification records the portability decisions in section 7.

  • No card data in errors. The PHP package writes the full card number into its error messages. This package never puts a card number or CVC in an error, a message or a string form. (card.errors-redacted)
  • Whitespace is removed before the brand is recognised, so 4111 1111 1111 1111 and 491 7300 8000 0000 give the same verdict as their compact forms. PHP matches the brand first and can reject a leading space or recognize a different brand when a space splits a prefix. (factory.whitespace)
  • One clock supplies the century for two-digit years and the comparison date, and a NUL byte is invalid input. PHP mixes the system clock with the test clock and trims NUL bytes. (expiration.year, expiration.month)
  • A card is an immutable validated value. A failed validation returns an error and no card, and 0 is checked as a one-digit number instead of being treated as unset. (card.construct-and-state)
  • Built-in brand rules are fixed and a custom brand is a typed specification. PHP exposes a public static pattern on each card class that a program can change, and an empty marker interface. (card.pattern-property, card.marker-contract)
  • A custom card is a typed specification checked when it is built, with the same checks as PHP's run-time checks on a subclass. (card.custom-implementation)
  • Both Hipercard prefix rules are anchored at the start of the number. PHP's second rule matches anywhere in the string, so some longer numbers fail on length in PHP and match no brand here. (brand.hipercard)
  • Rules are stateless. A reused expiration date rule reports the current failure. A reused card number rule has no failure message after a successful check. (rule.card-expiration-date.messages)
  • The date rule keeps the four-digit year as parsed, treats a NUL byte and a format token it does not support as malformed input, and needs a format with at least one token. PHP expands years below 100 to the current century, raises an uncaught error on NUL and parses every date-time token. (rule.card-expiration-date)
  • Rules return a default English message and export PHP's translation keys as constants. PHP returns the key itself and ships no translations. (rule.messages.translation)
  • Rules do not run on a null value: Laravel for Go skips a rule for a null or blank field, where PHP runs it on null. Add rule.Required for mandatory fields.
  • Go-specific whitespace behavior. The framework also skips non-implicit rules for a field consisting entirely of Unicode whitespace, including a non-breaking space. PHP runs the CVC rule on that value and rejects it.

Provenance

This package is an independent implementation of the behaviour of laravel-validation-rules/credit-card, which is licensed under Apache-2.0. It was written from public specifications and from the observed behaviour of the PHP package, and contains no code from it. The parity fixtures are outputs recorded by running the PHP package.

Installation and configuration

See the guide.

Compatibility

Module Framework Go
github.com/bowerbird-si/laravel-go-credit-card go.laravel.com v0.2.0 1.27

14 tests · 830 PHP fixtures · 5 fuzz targets (counted by kit readme)

Contributing

Issues and pull requests are welcome, of any size: bug reports, failing test cases, docs fixes, new features. Contributions written with AI coding agents are welcome too; please say what you checked. Run scripts/kit ci before opening a pull request, and see CONTRIBUTING.md. If you aren't sure, open an issue first.

Credits

Follows the behaviour of laravel-validation-rules/credit-card; see Provenance.

Status and licence

Maintenance status: active. MIT licensed, see LICENSE.

Community package, not affiliated with Laravel.

Documentation

Overview

Package creditcard validates credit card numbers, expiration dates and CVC codes for Laravel for Go, a Go port of laravel-validation-rules/credit-card.

Upstream: https://github.com/laravel-validation-rules/credit-card

Example

The README quick start. CI runs this example.

card, err := creditcard.Parse("4111 0000 0000 0008")
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(card.Brand(), card.Brand().Funding(), card)
Output:
Visa credit Visa card, 16 digits

Index

Examples

Constants

View Source
const (
	// KeyCardInvalid is PHP's MSG_CARD_INVALID key.
	KeyCardInvalid = "validation.credit_card.card_invalid"
	// KeyPatternInvalid is PHP's unused MSG_CARD_PATTER_INVALID key.
	KeyPatternInvalid = "validation.credit_card.card_pattern_invalid"
	// KeyLengthInvalid is PHP's MSG_CARD_LENGTH_INVALID key.
	KeyLengthInvalid = "validation.credit_card.card_length_invalid"
	// KeyChecksumInvalid is PHP's MSG_CARD_CHECKSUM_INVALID key.
	KeyChecksumInvalid = "validation.credit_card.card_checksum_invalid"
	// KeyCVCInvalid is PHP's MSG_CARD_CVC_INVALID key.
	KeyCVCInvalid = "validation.credit_card.card_cvc_invalid"
	// KeyExpirationYearInvalid is PHP's MSG_CARD_EXPIRATION_YEAR_INVALID key.
	KeyExpirationYearInvalid = "validation.credit_card.card_expiration_year_invalid"
	// KeyExpirationMonthInvalid is PHP's MSG_CARD_EXPIRATION_MONTH_INVALID key.
	KeyExpirationMonthInvalid = "validation.credit_card.card_expiration_month_invalid"
	// KeyExpirationDateInvalid is PHP's MSG_CARD_EXPIRATION_DATE_INVALID key.
	KeyExpirationDateInvalid = "validation.credit_card.card_expiration_date_invalid"
	// KeyExpirationDateFormatInvalid is PHP's MSG_CARD_EXPIRATION_DATE_FORMAT_INVALID key.
	KeyExpirationDateFormatInvalid = "validation.credit_card.card_expiration_date_format_invalid"
)
View Source
const Version = "0.1.0"

Version is the version of this module.

Variables

This section is empty.

Functions

func ValidCVC

func ValidCVC(value any) bool

ValidCVC checks for three or four digits, like PHP's CVC length helper. For example, "012" is valid.

func ValidCVCFor

func ValidCVCFor(number, cvc any) bool

ValidCVCFor checks the CVC against a valid card, like PHP's CardCvc. For example, an American Express number requires a four-digit CVC.

func ValidCVCLength

func ValidCVCLength(value any, lengths ...int) bool

ValidCVCLength checks against explicit lengths like PHP's isValidCvcLength. For example, ValidCVCLength("0123", 4) succeeds.

func ValidExpiration

func ValidExpiration(year, month any, now time.Time) bool

ValidExpiration reports whether a year and month are current or in the future as of now. It corresponds to PHP's CardExpirationDateValidator::validate.

func ValidExpirationDate

func ValidExpirationDate(value, format string, now time.Time) bool

ValidExpirationDate reports whether value is a well-formed and unexpired date in format, using the PHP CardExpirationDate rule's format tokens.

Types

type Brand

type Brand struct {
	// contains filtered or unexported fields
}

Brand is an immutable PHP card model definition. Look up Visa with BrandNamed("visa").

func BrandNamed

func BrandNamed(name string) (Brand, bool)

BrandNamed looks up a PHP card model by short name, for example "amex".

func Brands

func Brands() []Brand

Brands returns the PHP card models in recognition order, beginning with Dankort.

func Detect

func Detect(value any) (Brand, bool)

Detect recognizes the PHP card brand from a number's prefix. For example, Detect("411100") recognizes Visa before its length and checksum are checked.

func NewBrand

func NewBrand(spec BrandSpec) (Brand, error)

NewBrand checks a PHP-style custom card definition and returns an immutable brand.

func (Brand) DisplayName

func (b Brand) DisplayName() string

DisplayName returns the PHP model's display name, such as "Visa".

func (Brand) Funding

func (b Brand) Funding() Funding

Funding returns the PHP model's product type, such as Credit.

func (Brand) Name

func (b Brand) Name() string

Name returns the PHP card model's short name, such as "visa".

func (Brand) Parse

func (b Brand) Parse(value any) (Card, error)

Parse validates a number against this PHP card model, for example Visa's length, Luhn checksum and prefix requirements.

func (Brand) String

func (b Brand) String() string

String returns the PHP card model's display name.

func (Brand) ValidCVC

func (b Brand) ValidCVC(value any) bool

ValidCVC checks this PHP card model's CVC lengths, such as four for Amex.

type BrandSpec

type BrandSpec struct {
	Name, DisplayName   string
	Funding             Funding
	Pattern             string
	Lengths, CVCLengths []int
	Checksum            Checksum
}

BrandSpec describes a custom PHP-style card model. A Pattern such as ^77 lets the model match numbers beginning with 77.

type Card

type Card struct {
	// contains filtered or unexported fields
}

Card is an immutable validation result, corresponding to a PHP card model. It holds the brand and number length.

func Parse

func Parse(value any) (Card, error)

Parse detects the brand and validates a card number, like PHP's Factory::makeFromNumber. For example, Parse("4111 1111 1111 1111") returns a Visa.

func (Card) Brand

func (c Card) Brand() Brand

Brand returns the card's brand, for example the PHP Visa model.

func (Card) GoString

func (c Card) GoString() string

GoString renders the same redacted description as String under %#v.

func (Card) String

func (c Card) String() string

String describes a PHP card model with only its brand and digit count.

type Checksum

type Checksum uint8

Checksum selects the PHP card model's checksum behavior.

const (
	// Luhn requires the PHP card model's Luhn check.
	Luhn Checksum = iota + 1
	// NoChecksum skips Luhn, as PHP does for UnionPay.
	NoChecksum
)

type Error

type Error string

Error is a redacted validation category corresponding to a PHP card exception.

const (
	// ErrCardNotFound corresponds to PHP's card-not-found exception.
	ErrCardNotFound Error = "card_not_found"
	// ErrInvalidType indicates that PHP's string-or-integer contract was not met.
	ErrInvalidType Error = "invalid_type"
	// ErrEmpty corresponds to PHP's empty-card exception.
	ErrEmpty Error = "empty"
	// ErrCharacters corresponds to PHP's card-characters exception.
	ErrCharacters Error = "characters"
	// ErrLength corresponds to PHP's card-length exception.
	ErrLength Error = "length"
	// ErrChecksum corresponds to PHP's card-checksum exception.
	ErrChecksum Error = "checksum"
	// ErrPattern corresponds to PHP's card-pattern exception.
	ErrPattern Error = "pattern"
	// ErrFunding indicates an invalid PHP card product type.
	ErrFunding Error = "type"
	// ErrName indicates a missing PHP card name.
	ErrName Error = "name"
	// ErrCVCConfig indicates invalid PHP card CVC lengths.
	ErrCVCConfig Error = "cvc_config"
)

func (Error) Error

func (e Error) Error() string

Error returns a fixed category, for example "creditcard: length".

type Funding

type Funding string

Funding is the PHP card model's debit or credit type.

const (
	// Debit identifies a PHP debit card product such as Maestro.
	Debit Funding = "debit"
	// Credit identifies a PHP credit card product such as Visa.
	Credit Funding = "credit"
)

type Rule

type Rule struct {
	// contains filtered or unexported fields
}

Rule is a Laravel for Go validator corresponding to a PHP card rule. Use constructors like Number() and ExpirationDate("m/y").

func CVC

func CVC() Rule

CVC implements PHP CardCvc using the sibling card_number field.

func CVCFor

func CVCFor(number any) Rule

CVCFor implements PHP CardCvc with an explicit number. Only its validated brand is retained.

func CVCFrom

func CVCFrom(path string) Rule

CVCFrom implements PHP CardCvc using a relative field path such as "number".

func ExpirationDate

func ExpirationDate(phpFormat string) Rule

ExpirationDate implements PHP CardExpirationDate using a PHP format such as "m/y".

func ExpirationMonth

func ExpirationMonth() Rule

ExpirationMonth implements PHP CardExpirationMonth with the sibling expiration_year field.

func ExpirationMonthFor

func ExpirationMonthFor(year any) Rule

ExpirationMonthFor implements PHP CardExpirationMonth with an explicit year, such as "28".

func ExpirationMonthFrom

func ExpirationMonthFrom(path string) Rule

ExpirationMonthFrom implements PHP CardExpirationMonth with a relative field path such as "year".

func ExpirationYear

func ExpirationYear() Rule

ExpirationYear implements PHP CardExpirationYear with the sibling expiration_month field.

func ExpirationYearFor

func ExpirationYearFor(month any) Rule

ExpirationYearFor implements PHP CardExpirationYear with an explicit month, such as 12.

func ExpirationYearFrom

func ExpirationYearFrom(path string) Rule

ExpirationYearFrom implements PHP CardExpirationYear with a relative field path such as "month".

func Number

func Number() Rule

Number implements the PHP CardNumber rule as a Laravel for Go rule.

func (Rule) Message

func (r Rule) Message(text string) Rule

Message returns a rule with one message for every failure, analogous to replacing the PHP rule's translation text.

func (Rule) MessageFor

func (r Rule) MessageFor(key, text string) Rule

MessageFor returns a rule with a message for one PHP translation key. For example, Number().MessageFor(KeyLengthInvalid, "Check the number of digits.").

func (Rule) Validate

func (r Rule) Validate(ctx context.Context, field validation.Field) error

Validate checks a Laravel field and returns a failure for the corresponding PHP message category. Expiration rules expect a Laravel application context.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL