card-validator

A library for validating credit card fields

Credit Card Validator

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 maxlengthattribute of your CVVinput element from 3 to 4 and even update the corresponding labelfrom 'CVV' to 'CID'.

Download

You can install card-validatorthrough 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 luhnValidateUnionPayas 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 maxLengthas 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 maxLengthof 16is provided, the validator will still use 15as 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 cardfield in the response will be null.

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

InputOutputSuggested Handling
Valuecard.typeisPotentiallyValidisValidRender Invalid UIAllow Submit
''nulltruefalsenono
'6'nulltruefalsenono
'60''discover'truefalsenono
'601''discover'truefalsenono
'6011''discover'truefalsenono
'601''discover'truefalsenono
'60''discover'truefalsenono
'6'nulltruefalsenono
''nulltruefalsenono
'x'nullfalsefalseyesno
''nulltruefalsenono
'4''visa'truefalsenono
'41''visa'truefalsenono
'411''visa'truefalsenono
'4111111111111111''visa'truetruenoyes
'411x'nullfalsefalseyesno

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

The maxElapsedYearhas a default value of 19. It can be overridden by passing in an integeras 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
}

expirationDatewill parse strings in a variety of formats:

InputOutput
'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: '10', year: '2019'}
{month: '1', year: '2019'}
{month: 1, year: 19}
{month: '10', year: '2019'}

valid.expirationMonth(value: string): object

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

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

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

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

The maxElapsedYearhas a default value of 19. It can be overridden by passing in an integeras a second argument.

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

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

The cvvvalidation by default tests for a numeric string of 3 characters in length. The maxLengthcan be overridden by passing in an integeras 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 postalCodevalidation essentially tests for a valid string greater than 3 characters in length.

{
  isPotentiallyValid: true,
  isValid: true
}

You can optionally pass minLengthas 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-typemoduleas creditCardType. You can add custom card brands by utilizing the addCardmethod.

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.expirationDatewill 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 postalCodewill allow non-number characters to be used in validation.

Development

We use nvmfor managing our node versions, but you do not have to. Replace any nvmreferences 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.

HomePage

https://github.com/braintree/card-validator

Repository

https@github.com:braintree/card-validator


上一篇:moment-jalaali
下一篇:【TypeScript 演化史 -- 3】标记联合类型 与 never 类型

相关推荐

  • 详解vue-validator(vue验证器)

    官方文档:http://vuejs.github.io/vuevalidator/zhcn/index.html(http://vuejs.github.io/vuevalidator/zhcn/in...

    3 年前
  • 设计一个好用的Validator

    其实很少在周末写文章的,更别谈玩前端了。既然给自己下了个目标,每个星期产出两篇文章,就要尽量做到呗。这次我讲一个验证器的设计思路,也是一年前就造出来的小轮子(ManitoYu/ycvalidator(...

    2 年前
  • 有意思的异步校验async-validator

    asyncvalidator 是个纯 js 库,可以对数据进行异步校验。asyncvalidator 是基于早期的 asyncvalidate 进行修改的,但是早期出现的 asyncvalidate ...

    4 个月前
  • 开源ReactNative卡片式(Cards)组件,你值得拥有

    开源一个跨端的卡片式设计(Cards)的组件,在Android中是Material Design中有一种很个性的设计概念,在使用ReactNative跨平台的开发框架中,卡片样式在IOS平台通过设置V...

    9 个月前
  • yairEO-validator

    yairEOvalidator是什么 什么是yairEOvalidator,The Validator is crossbrowser and will give you the power to...

    2 年前
  • xsd-schema-validator

    A (XSD) schema validator for nodejs xsdschemavalidator Build Status(https://travisci.org/nikku/no...

    1 年前
  • xml-name-validator

    Validates whether a string matches the production for an XML name or qualified name Validate XML N...

    2 年前
  • wildcards

    emitter wildcard support wildcards Wildcard eventemitter proxy for nodejs. Installation E...

    4 个月前
  • wildcard2

    Wildcard2 A wildcard match module. Quickstart Install Examples That's it Contribute l...

    7 个月前
  • wildcard

    Wildcard matching tools wildcard Very simple wildcard matching, which is designed to provide the...

    7 个月前

官方社区

扫码加入 JavaScript 社区