• Stars
    star
    822
  • Rank 54,132 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 9 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Validate credit cards as users type.

Credit Card Validator Build Status npm version

Credit Card Validator provides validation utilities for credit card data inputs. It is designed as a CommonJS module for use in Node.js, io.js, or the browser. It includes first class support for 'potential' validity so you can use it to present appropriate UI to your user as they type.

A typical use case in a credit card form is to notify the user if the data they are entering is invalid. In a credit card field, entering โ€œ411โ€ is not necessarily valid for submission, but it is still potentially valid. Conversely, if a user enters โ€œ41xโ€ that value can no longer pass strict validation and you can provide a response immediately.

Credit Card Validator will also provide a determined card type (using credit-card-type). This is useful for scenarios in which you wish to render an accompanying payment method icon (Visa, MasterCard, etc.). Additionally, by having access to the current card type, you can better manage the state of your credit card form as a whole. For example, if you detect a user is entering (or has entered) an American Express card number, you can update the maxlength attribute of your CVV input element from 3 to 4 and even update the corresponding label from 'CVV' to 'CID'.

Download

You can install card-validator through npm.

npm install card-validator

Example

Using a CommonJS build tool (browserify, webpack, etc)

var valid = require("card-validator");

var numberValidation = valid.number("4111");

if (!numberValidation.isPotentiallyValid) {
  renderInvalidCardNumber();
}

if (numberValidation.card) {
  console.log(numberValidation.card.type); // 'visa'
}

API

var valid = require('card-validator');


valid.number(value: string, [options: object]): object

{
  card: {
    niceType: 'American Express',
    type: 'american-express',
    gaps: [4, 10],
    lengths: [15],
    code: {name: 'CID', size: 4}
  },
  isPotentiallyValid: true, // if false, indicates there is no way the card could be valid
  isValid: true // if true, number is valid for submission
}

You can optionally pass luhnValidateUnionPay as a property of an object as a second argument. This will override the default behavior to ignore luhn validity of UnionPay cards.

valid.number(<Luhn Invalid UnionPay Card Number>, {luhnValidateUnionPay: true});

{
  card: {
    niceType: 'UnionPay',
    type: 'unionpay',
    gaps: [4, 8, 12],
    lengths: [16, 17, 18, 19],
    code: {name: 'CVN', size: 3}
  },
  isPotentiallyValid: true,
  isValid: false // Would be true if no options were included
}

You can optionally pass maxLength as a property of an object as a second argument. This will override the default behavior to use the card type's max length property and mark any cards that exceed the max length as invalid.

If a card brand has a normal max length that is shorter than the passed in max length, the validator will use the shorter one. For instance, if a maxLength of 16 is provided, the validator will still use 15 as the max length for American Express cards.

valid.number(<Maestro Card with 19 Digits>, {maxLength: 16});

{
  card: {
    // Maestro card data
  },
  isPotentiallyValid: false,
  isValid: false
}

If a valid card type cannot be determined, the card field in the response will be null.

A fake session where a user is entering a card number may look like:

Input Output Suggested Handling
Value card.type isPotentiallyValid isValid Render Invalid UI Allow Submit
'' null true false no no
'6' null true false no no
'60' 'discover' true false no no
'601' 'discover' true false no no
'6011' 'discover' true false no no
'601' 'discover' true false no no
'60' 'discover' true false no no
'6' null true false no no
'' null true false no no
'x' null false false yes no
'' null true false no no
'4' 'visa' true false no no
'41' 'visa' true false no no
'411' 'visa' true false no no
'4111111111111111' 'visa' true true no yes
'411x' null false false yes no

valid.cardholderName(value: string): object

The cardholderName validation essentially tests for a valid string greater than 0 characters in length that does not look like a card number.

{
  isPotentiallyValid: true,
  isValid: true
}

If a cardholder name is comprised of only numbers, hyphens and spaces, the validator considers it to be too card-like to be valid, but may still be potentially valid if a non-numeric character is added. This is to prevent card number values from being sent along as the cardholder name but not make too many assumptions about a person's cardholder name.

{
  isPotentiallyValid: true,
  isValid: false
}

If a cardholder name is longer than 255 characters, it is assumed to be invalid.

{
  isPotentiallyValid: false,
  isValid: false
}

valid.expirationDate(value: string|object, maxElapsedYear: integer): object

The maxElapsedYear parameter determines how many years in the future a card's expiration date should be considered valid. It has a default value of 19, so cards with an expiration date 20 or more years in the future would not be considered valid. It can be overridden by passing in an integer as a second argument.

{
  isPotentiallyValid: true, // if false, indicates there is no way this could be valid in the future
  isValid: true,
  month: '10', // a string with the parsed month if valid, null if either month or year are invalid
  year: '2016' // a string with the parsed year if valid, null if either month or year are invalid
}

expirationDate will parse strings in a variety of formats:

Input Output
'10/19'
'10 / 19'
'1019'
'10 19'
{month: '10', year: '19'}
'10/2019'
'10 / 2019'
'102019'
'10 2019'
'10 19'
{month: '10', year: '2019'}
'2019-10' {month: '10', year: '2019'}
{month: '01', year: '19'}
{month: '1', year: '19'}
{month: 1, year: 19}
{month: '01', year: '19'}
{month: '01', year: '2019'}
{month: '1', year: '2019'}
{month: 1, year: 2019}
{month: '01', year: '2019'}

valid.expirationMonth(value: string): object

expirationMonth accepts 1 or 2 digit months. 1, 01, 10 are all valid entries.

{
  isValidForThisYear: false,
  isPotentiallyValid: true,
  isValid: true
}

valid.expirationYear(value: string, maxElapsedYear: integer): object

expirationYear accepts 2 or 4 digit years. 16 and 2016 are both valid entries.

The maxElapsedYear parameter determines how many years in the future a card's expiration date should be considered valid. It has a default value of 19, so cards with an expiration date 20 or more years in the future would not be considered valid. It can be overridden by passing in an integer as a second argument.

{
  isCurrentYear: false,
  isPotentiallyValid: true,
  isValid: true
}

valid.cvv(value: string, maxLength: integer): object

The cvv validation by default tests for a numeric string of 3 characters in length. The maxLength can be overridden by passing in an integer as a second argument. You would typically switch this length from 3 to 4 in the case of an American Express card which expects a 4 digit CID.

{
  isPotentiallyValid: true,
  isValid: true
}

valid.postalCode(value: string, [options: object]): object

The postalCode validation essentially tests for a valid string greater than 3 characters in length.

{
  isPotentiallyValid: true,
  isValid: true
}

You can optionally pass minLength as a property of an object as a second argument. This will override the default min length of 3.

valid.postalCode('123', {minLength: 5});

{
  isPotentiallyValid: true,
  isValid: false
}

Custom Card Brands

Card Validator exposes the credit-card-type module as creditCardType. You can add custom card brands by utilizing the addCard method.

valid.creditCardType.addCard({
  niceType: "NewCard",
  type: "new-card",
  patterns: [1234],
  gaps: [4, 8, 12],
  lengths: [16],
  code: {
    name: "CVV",
    size: 3,
  },
});

Design decisions

  • The default maximum expiration year is 19 years from now.
  • valid.expirationDate will only return month: and year: as strings if the two are valid, otherwise they will be null.
  • Since non-US postal codes are alpha-numeric, the postalCode will allow non-number characters to be used in validation.

Development

We use nvm for managing our node versions, but you do not have to. Replace any nvm references with the tool of your choice below.

nvm install
npm install

All testing dependencies will be installed upon npm install. Run the test suite with npm test.

More Repositories

1

manners

A polite Go HTTP server that shuts down gracefully.
Go
987
star
2

credit-card-type

A library for determining credit card type
TypeScript
916
star
3

runbook

A framework for gradual system automation
Ruby
700
star
4

braintree_ios

Braintree SDK for iOS
Swift
542
star
5

braintree_php

Braintree PHP library
PHP
535
star
6

braintree_ruby

Braintree Ruby library
Ruby
430
star
7

braintree_android

Braintree SDK for Android
Java
402
star
8

android-card-form

A ready-made card form layout that can be included in your Android app, making it easy to accept credit and debit cards.
Java
360
star
9

curator

Model and repository framework
Ruby
354
star
10

braintree_node

Braintree Node.js library
JavaScript
325
star
11

sanitize-url

TypeScript
253
star
12

braintree_python

Braintree Python library
Python
235
star
13

pg_ha_migrations

Enforces DDL/migration safety in Ruby on Rails project with an emphasis on explicitly choosing trade-offs and avoiding unnecessary magic.
Ruby
182
star
14

braintree_express_example

An example Braintree integration for Express
CSS
175
star
15

jsdoc-template

A clean, responsive documentation template with search and navigation highlighting for JSDoc 3
CSS
172
star
16

framebus

A message bus that operates across iframes
TypeScript
150
star
17

braintree_java

Braintree Java library
Java
147
star
18

braintree_dotnet

Braintree .NET library
C#
132
star
19

braintree_php_example

An example Braintree integration for PHP
CSS
124
star
20

braintree-android-drop-in

Braintree Drop-In SDK for Android
Java
118
star
21

braintree_flask_example

An example Braintree integration for Flask
CSS
103
star
22

braintree-ios-drop-in

Braintree Drop-in for iOS
Objective-C
97
star
23

braintree_rails_example

An example Braintree integration for Ruby on Rails
HTML
85
star
24

braintree_spring_example

An example Braintree integration for Spring (Java)
CSS
80
star
25

braintree-encryption.js

Javascript Library for Client-side Encryption with Braintree
JavaScript
77
star
26

pg_column_byte_packer

Auto-order table columns for optimize disk space usage
Ruby
71
star
27

restricted-input

Restrict <input>s to certain valid characters (e.g. formatting phone or card numbers)
TypeScript
66
star
28

browser-detection

A utility for detecting browsers in Braintree libs.
TypeScript
60
star
29

braintree_aspnet_example

An example Braintree integration in the ASP.NET framework
CSS
59
star
30

graphql-api

Schemas, changelogs and feature requests for Braintree's GraphQL API
57
star
31

mallory

Reverse proxy for HTTPS services, with SSL verification.
Python
57
star
32

us-bank-account-validator

A library for validating US bank account routing and account numbers
TypeScript
51
star
33

popup-bridge-android

PopupBridge allows WebViews to open popup windows in a browser and send data back to the WebView
Java
49
star
34

popup-bridge-ios

Enable your web view to open pages in a Safari View Controller
Swift
32
star
35

litmus_paper

Backend health tester for HA Services
Ruby
32
star
36

open_api_parser

A parser for Open API specifications
Ruby
30
star
37

big_brother

a daemon to monitor and administer servers in a LVS cluster of load balanced virtual servers
Ruby
28
star
38

mysql_to_postgresql

ruby script which migrates data from a MySQL database to PostgreSQL
Ruby
26
star
39

fake-wallet-app-ios

A fake version of the {PayPal,Venmo} Wallet for development
Objective-C
25
star
40

braintree_android_encryption

braintree_android_encryption
Java
24
star
41

browser-switch-android

Open a url in a browser or Chrome Custom Tab and receive a response as the result of user interaction.
Java
23
star
42

braintree_slim_example

An example Braintree integration for Slim (PHP)
CSS
22
star
43

form-napper

Hijack, submit, and inject data into forms.
JavaScript
21
star
44

braintree_perl

Braintree Perl library
Perl
18
star
45

braintree-auth-example

A Ruby/Sinatra application that demonstrates the Braintree Auth API
JavaScript
17
star
46

curator_rails_example

Example Rails application for curator
Ruby
16
star
47

activerecord-postgresql-citext

citext support for rails 4
Ruby
15
star
48

braintreehttp_php

PHP
15
star
49

wrap-promise

Small module to help support APIs that return a promise or use a callback.
TypeScript
15
star
50

iframer

Create consistent iframes
TypeScript
14
star
51

mallorca

Man-in-the-middle proxying for HTTPS.
JavaScript
14
star
52

braintree_graphql_rails_example

An example Braintree integration with the GraphQL API using Ruby on Rails
HTML
14
star
53

inject-stylesheet

Create a <style> element with CSS properties, filtering input using an allowlist or blocklist.
TypeScript
14
star
54

apollo-tracing-uploader-java

Upload Java GraphQL tracing metrics to Apollo Graph Manager
Java
13
star
55

braintree_client_side_encryption

javascript library for client-side encryption with braintree
JavaScript
13
star
56

braintree-ios-visa-checkout

Visa Checkout component for our Braintree iOS SDK
Objective-C
9
star
57

braintree_android_encryption_examples

Java
8
star
58

braintree-web-bower

JavaScript
8
star
59

braintree-android-visa-checkout

Visa Checkout component for our Braintree Android SDK
Java
7
star
60

spidersuite

Configurable crawler and reporting tool for verifying websites
JavaScript
6
star
61

eslint-config

Shared linting configuration for braintree js projects
TypeScript
5
star
62

qsagi

A friendly way to talk to RabbitMQ
Ruby
5
star
63

braintree-types

TypeScript definitions for Braintree Custom Actions
TypeScript
4
star
64

heckler

Heckler's aim is to allow you to correlate code changes with Puppet noop output!
Go
4
star
65

braintree.github.io

Braintree open source website
HTML
3
star
66

braintreehttp_python

Python
3
star
67

braintreehttp_java

Java
3
star
68

event-emitter

A simple JS based event emitter
TypeScript
3
star
69

asset-loader

A module to load frontend assets.
TypeScript
3
star
70

braintree_windows_phone_encryption

.net library for client-side encryption with braintree
C#
2
star
71

braintreehttp_ruby

Ruby
2
star
72

class-list

A helper for applying classes to dom nodes.
TypeScript
2
star
73

fluent-plugin-s3

Ruby
2
star
74

braintree-android-samsung-pay

Samsung Pay component for our Braintree Android SDK
Java
2
star
75

braintreehttp_node

JavaScript
1
star
76

extended-promise

TypeScript
1
star
77

braintree-web-drop-in-bower

Braintree Drop-in for the web
JavaScript
1
star
78

webhint-configuration-braintree-sdk

Beta Webhint configuration for Braintree's sdk-related packages
1
star
79

destructor

TypeScript
1
star
80

braintree_windows_phone_encryption_examples

C#
1
star
81

credit-card-form

Name TBD
1
star
82

popup-bridge-example

Example site for Popup Bridge mobile library
HTML
1
star
83

uuid

A simple node js implementation of uuid v4 for use with Braintree's JS based SDKs.
JavaScript
1
star