• Stars
    star
    100
  • Rank 340,703 (Top 7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated over 5 years ago

Reviews

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

Repository Details

Credit card validation

credit-card

Current Version Build Status via Travis CI Dependencies belly-button-style

Module for performing credit card validation.

Basic Usage

Pass credit card information to the validate() method. In the following example, the credit card information is stored in card.

var CreditCard = require('credit-card');
var card = {
  cardType: 'VISA',
  number: '4111111111111111',
  expiryMonth: '03',
  expiryYear: '2100',
  cvv: '123'
};
var validation = CreditCard.validate(card);

The validation object returned by validate() will look like this:

{
  card: {
    cardType: 'VISA',
    number: '4111111111111111',
    expiryMonth: '03',
    expiryYear: '2100',
    cvv: '123'
  },
  validCardNumber: true,
  validExpiryMonth: true,
  validExpiryYear: true,
  validCvv: true,
  isExpired: false
}

Methods

validate(card [, options])

  • Arguments
    • card (object) - An object containing credit card information. Should be of the following format:
      • cardType (string) - One of the supported card types.
      • number (string) - Credit card number.
      • expiryMonth (string or number) - Credit card expiration month.
      • expiryYear (string or number) - Credit card expiration year.
      • cvv (string) - Credit card CVV code.
    • options (object) - An optional object used to define custom card types and default values. Can define the following fields:
      • cardTypes (object) - An object used to validate credit card types. This allows new types, such as custom gift cards, to be defined.
      • expiryMonths (object) - An object used to override default values related to expiry months.
      • expiryYears (object) - An object used to override default values related to expiry years.
      • schema (object) - An object defining the names of the expected card property names. This is useful for supporting card data in a slightly different format. This can define cardType, number, expiryMonth, expiryYear, and cvv names.
  • Returns
    • object - An object containing the input card data and the results of validation. Should adhere to the following schema:
      • card (object) - This holds the value of the card argument.
      • validCardNumber (boolean) - The result of calling isValidCardNumber().
      • validExpiryMonth (boolean) - The result of calling isValidExpiryMonth().
      • validExpiryYear (boolean) - The result of calling isValidExpiryYear().
      • validCvv (boolean) - The result of calling doesCvvMatchType().
      • isExpired (boolean) - The result of calling isExpired().
      • customValidation (any) - The result of custom validation. Can be any data type.

Performs several validation checks on credit card data.

determineCardType(number [, options])

  • Arguments
    • number (string) - Credit card number string. This value is passed to sanitizeNumberString() prior to classification.
    • options (object) - An optional object used to pass in additional options. The following options are supported.
      • allowPartial (boolean) - If true, then partial matches are accepted. Otherwise, only full length credit card numbers are accepted. Defaults to false.
  • Returns
    • string - a string representing the card type. If no type matches the number, then null is returned.

Given a credit card number, this function attempts to determine the card type.

isValidCardNumber(number, type [, options])

  • Arguments
    • number (string) - Credit card number string.
    • type (string) - Credit card type.
    • options (object) - An optional object used to define additional card types.
  • Returns
    • boolean - true if the number is valid for the credit card type and passes the Luhn algorithm, false otherwise.

Determines if a credit card number is valid for a given credit card type. Also verifies that the credit card number passes the Luhn algorithm.

isValidExpiryMonth(month [, options])

  • Arguments
    • month (number or string) - Month value to be evaluated.
    • options (object) - An optional object used to define the minimum and maximum month values accepted.
  • Returns
    • boolean - true if month is a valid expiry month, false otherwise.

Determines if a value is a valid credit card expiry month. The month must fall between the defined minimum and maximum months. This range is 1 to 12 by default, but can be adjusted using the options input.

isValidExpiryYear(year [, options])

  • Arguments
    • year (number or string) - Year value to be evaluated.
    • options (object) - An optional object used to define the minimum and maximum year values accepted.
  • Returns
    • boolean - true if year is a valid expiry month, false otherwise.

Determines if a value is a valid credit card expiry year. The year must fall between the defined minimum and maximum years. This range is 1900 to 2200 by default, but can be adjusted using the options input.

doesNumberMatchType(number, type [, options])

  • Arguments
    • number (string) - Credit card number string.
    • type (string) - Credit card type.
    • options (object) - An optional object used to define additional card types.
  • Returns
    • boolean - true if the number is valid for the credit card type, false otherwise.

Determines if a credit card number is valid for a given credit card type.

doesCvvMatchType(number, type [, options])

  • Arguments
    • number (string) - CVV string.
    • type (string) - Credit card type.
    • options (object) - An optional object used to define additional card types.
  • Returns
    • boolean - true if the CVV is valid for the credit card type, false otherwise.

Determines if a CVV is valid for a given credit card type. For example, American Express requires a four digit CVV, while Visa and Mastercard require a three digit CVV.

isExpired(month, year)

  • Arguments
    • month (number) - Expiry month of card.
    • year (number) - Expiry year of card.
  • Returns
    • boolean - true if the expiration date has been reached, false otherwise.

Determines if a credit card's expiration date has been reached.

luhn(number)

  • Arguments
    • number (string) - The number string to check.
  • Returns
    • boolean - true if the number passes, false otherwise.

Executes the Luhn algorithm on a string to determine if it is a valid credit card number.

sanitizeNumberString(number)

  • Arguments
    • number (string) - The number string to be sanitized.
  • Returns
    • string - The sanitized string.

Strips all non-numeric characters from number. If number is not a string, an empty string is returned.

defaults([options [, overwrite]])

  • Arguments
    • options (object) - New default values.
    • overwrite (boolean) - If true, options completely overwrites the current defaults. Otherwise, options is merged into the current defaults.
  • Returns
    • object - The module's default settings following the update.

Sets module level default values. The existing defaults can be augmented or overwritten completely based on the value of overwrite. To restore the original default values, call reset().

reset()

  • Arguments
    • None
  • Returns
    • object - The module's original default settings.

Resets the module's default settings to their original values. This can be useful for undoing the effects of defaults().

Supported Credit Card Types

This module supports a variety of credit cards. To better accommodate a wider range of clients, the card types have been aliased to other names as well.

  • VISA - Aliased to vc, VC, and visa.
  • MASTERCARD - Aliased to mc, MC, mastercard, master card, and MASTER CARD.
  • AMERICANEXPRESS - Aliased to ae, AE, ax, AX, amex, AMEX, american express, and AMERICAN EXPRESS.
  • DINERSCLUB - Aliased to dinersclub.
  • DISCOVER - Aliased to dc, DC, and discover.
  • JCB - Aliased to jcb.

Defining Custom Card Types

The following example defines and validates a new card type known as GIFT_CARD. Notice that the card variable has its cardType set to GIFT_CARD, and a new pin field has been defined. The options variable is passed as the second argument to validate(). These options define the new GIFT_CARD type. The cardPattern is a regular expression that all complete gift card numbers should match. partialPattern is the minimal regular expression that can be used to detect a gift card. cvvPattern is a regular expression that the complete CVV should match.

Also notice the customValidation function. This function is used when normal validation is not quite enough. This function is passed the card object and settings object used by validate(). This function can return any data, which will be added directly to the response.

This can be done globally, or on a per validation call basis. This example shows how it is done on a per call basis. To achieve the same thing globally, use the defaults() methods.

var CreditCard = require('credit-card');
var card = {
  cardType: 'GIFT_CARD',
  number: '4111111111111111',
  expiryMonth: '03',
  expiryYear: '2100',
  pin: '7890'
};
var options = {
  cardTypes: {
    GIFT_CARD: {
      cardPattern: /^4[0-9]{12}(?:[0-9]{3})?$/,
      partialPattern: /^4/,
      cvvPattern: /.*/
    }
  },
  customValidation: function(card, settings) {
    if (card.cardType === 'GIFT_CARD') {
      return card.pin === '7890';
    }
  }
};
var validation = CreditCard.validate(card, options);

The value of validation is shown below.

{
  card: {
    cardType: 'GIFT_CARD',
    number: '4111111111111111',
    expiryMonth: '03',
    expiryYear: '2100',
    pin: '7890'
  },
  validCardNumber: true,
  validExpiryMonth: true,
  validExpiryYear: true,
  validCvv: true,
  isExpired: false,
  customValidation: true
}

Defining a Custom Card Schema

By default, the validate() method expects the credit card object to contain the fields cardType, number, expiryMonth, expiryYear, and cvv. However, for convenience when working with other APIs, the module can be configured to use different field names. These overrides can be applied globally using defaults(), or on a per validation call using the options argument.

The following example shows how CreditCard can be configured to work with the PayPal schema by default. Notice that the fields in the schema passed to defaults() correspond to the fields in the card object.

var card = {
  type: 'visa',
  number: '4111111111111111',
  expire_month: '03',
  expire_year: '2100',
  cvv2: '123'
};
var validation;

CreditCard.defaults({
  schema: {
    cardType: 'type',
    number: 'number',
    expiryMonth: 'expire_month',
    expiryYear: 'expire_year',
    cvv: 'cvv2'
  }
});
validation = CreditCard.validate(card);

Test Card Numbers

A list of test credit cards is available from PayPal.

More Repositories

1

jsparser

An ECMAScript 5.1 parser, written in JavaScript. The ECMAScript grammar was created using Jison.
JavaScript
97
star
2

grpc-server-js

Pure JavaScript gRPC Server
JavaScript
61
star
3

node-v8-inspector

Chrome extension for launching V8 Inspector for Node.js debugging
JavaScript
53
star
4

toolbag

preloaded Node.js tooling enhancements
JavaScript
41
star
5

hapi-gateway

use hapi as a gateway to lambda functions
JavaScript
31
star
6

will-it-optimize

Suite of tests for determining what v8 will optimize
JavaScript
25
star
7

nuisance

hapi authentication requiring multiple strategies
JavaScript
21
star
8

shinobi

Simple, fun, memory safe language.
C++
16
star
9

zipit

Easily create zip archives
JavaScript
13
star
10

validate-directive

A GraphQL directive for input validation
JavaScript
12
star
11

belly-button

The best source for lint
JavaScript
12
star
12

bcrypt.wasm

bcrypt in WebAssembly
C++
12
star
13

wasi-worker

Node.js worker for running WASI code
JavaScript
11
star
14

webserial

Web Serial API for Node.js
C
10
star
15

stand-in

Method replacement and testing utility
JavaScript
10
star
16

noops

Deploy an API server as multiple AWS lambda functions
JavaScript
9
star
17

scrabel

Babel transpilation as needed
JavaScript
9
star
18

grpc-benchmarking

Benchmarking, but for gRPC
Rust
9
star
19

artificial

Inject fake HTTP request/response into an Express server
JavaScript
9
star
20

swagger-jacker

Express API documentation generator
JavaScript
8
star
21

walloc

malloc() and free() bindings for WebAssembly in JavaScript.
JavaScript
7
star
22

lambundaler

Bundler for AWS Lambda functions
JavaScript
7
star
23

reach

Safely retrieve nested object keys
JavaScript
7
star
24

ghostbuster

A Node.js wrapper for PhantomJS
JavaScript
7
star
25

server-timi

Server timing API plugin for hapi
JavaScript
6
star
26

wequire

synchronously load wasm files
JavaScript
5
star
27

helper.js

A lightweight, client-side scripting library.
4
star
28

acceleration

Acceleration Templating Language
JavaScript
4
star
29

kneejerk

Server Side React Render
JavaScript
3
star
30

userinfo

Node.js native addon for working with user information
C++
3
star
31

graylogi

Graylog logger for hapi
JavaScript
3
star
32

nodeginx

Node.js in an nginx module
C
3
star
33

farmhash.wasm

WebAssembly implementation of Google FarmHash
C++
3
star
34

pgee

PostgreSQL Asynchronous Notification Event Emitter
JavaScript
3
star
35

versionly

App version data generator
JavaScript
2
star
36

isgreen

Is your io.js installation up to date
JavaScript
2
star
37

exploder

Express port of Boom
JavaScript
2
star
38

dynamodb-stream-emitter

EventEmitter adapter for DynamoDB streams
JavaScript
2
star
39

toolbag-plugins

A collection of toolbag plugins
JavaScript
2
star
40

olympics

A module written during the Olympics
JavaScript
2
star
41

node-push-notification

Multi-platform capable push notifications using Node.js
JavaScript
2
star
42

augmented-interval-tree

Augmented interval tree implementation with no dependencies
JavaScript
2
star
43

rollover

hapi 17+ rollbar plugin
JavaScript
2
star
44

metri

hapi plugin for returning Node.js process metrics
JavaScript
2
star
45

semafour

Node.js semaphore
JavaScript
2
star
46

extra-silly-modules

Extra Silly Modules
JavaScript
2
star
47

enforce-node-version

npm script to enforce the engines.node field in package.json
JavaScript
2
star
48

sleep.wasm

sleep in WebAssembly
JavaScript
1
star
49

promise-throw

Turn process Promise events into thrown exceptions
JavaScript
1
star
50

webconsole-node-old

Node.js run by ContainerPilot
JavaScript
1
star
51

trivial-multipart

Very simple multipart form data
1
star
52

lambstaller

Run npm install locally in a Lambda container
JavaScript
1
star
53

nginx-node-cp

nginx and Node.js in a single container managed by ContainerPilot
JavaScript
1
star
54

fishsticks

Parse Node core compatible git info
JavaScript
1
star
55

thin-mint

HTTP cookie utility
JavaScript
1
star
56

hapi-auth-signi

hapi authentication scheme for validating signed requests
JavaScript
1
star
57

node-process-metrics-prometheus

retrieve Node.js process metrics in exposition format
JavaScript
1
star
58

scrapey

Web page scraping utility written in Node.js
JavaScript
1
star
59

gelfie

GELF client
JavaScript
1
star
60

examination

Thoroughly examine the state of a Node.js process
JavaScript
1
star
61

toolbag-plugin-policy

toolbag plugin that allows blacklisting of modules, methods, and bindings
JavaScript
1
star
62

toolbag-plugin-stats-collector

Toolbag plugin that collects runtime metrics
JavaScript
1
star
63

borland

hapi plugin for working with toolbag
JavaScript
1
star
64

hapi-publish-bot

Slack bot that creates notifications for npm publish events
JavaScript
1
star
65

who-set-it

Track where object properties are assigned
JavaScript
1
star
66

test-runner-ecosystem

node:test with various ecosystem modules
JavaScript
1
star