A simple credit cards validation library in JavaScript

Overview

creditcard.js

Build Status Dependency Status devDependency Status npm

A simple credit cards validation library in JavaScript.

Project website: https://contaazul.github.io/creditcard.js

Install

creditcard.js is available as a NPM package. You can install through Yarn or NPM:

Yarn

$ yarn add creditcard.js

NPM

$ npm install creditcard.js

Usage

import {
  isValid,
  isExpirationDateValid,
  isSecurityCodeValid,
  getCreditCardNameByNumber,
} from 'creditcard.js';

isValid('4916108926268679'); // returns true
isExpirationDateValid('02', '2020'); // returns true
isSecurityCodeValid('4556603578296676', '250'); // returns true
getCreditCardNameByNumber('4539578763621486'); // returns 'Visa'

Methods

isValid(number) -> boolean

Checks whether the credit card number format is valid. (See the full list of currently supported cards)

number

Required
Type: string

options

Optional
Type: { cards: string[] }


isExpirationDateValid(month, year) -> boolean

Checks that the expiration date is valid and not expired. (2 or 4 digit years are accepted)

month

Required
Type: string

year

Required
Type: string


isSecurityCodeValid(creditCardNumber, securityCode) -> boolean

Check that the security code is valid according to the type of credit card.

creditCardNumber

Required
Type: string

securityCode

Required
Type: string


getCreditCardNameByNumber(number) -> string

Returns the credit card type from the card number. (See the full list of currently supported cards)

number

Required
Type: string


Suportted credit card types

  • American Express
  • Aura
  • Banescard
  • Cabal
  • Diners
  • Discover
  • Elo
  • Goodcard
  • Hipercard
  • Mastercard
  • Maxxvan
  • Visa

License

MIT © Conta Azul

Comments
  • added new bins to 'MasterCard'

    added new bins to 'MasterCard'

    New initial digits will be available in October for Mastercard : 222100 - 222199 222200 - 222999 223000 - 229999 230000 - 269999 270000 - 271999 272000 - 272099

    opened by ronaldoflima 10
  • Adicionando novas bandeiras

    Adicionando novas bandeiras

    Adicionando as bandeiras Maestro e Visa Electron.

    Adicionei essas bandeiras e também seus respectivos testes. Qualquer dúvida estou a disposição !

    Parabéns pela Lib!

    opened by washingtonsoares 9
  • Automatically update release with npm script

    Automatically update release with npm script

    We're make changes and not updating releases in npm and bower. How we can work with that?

    There is a problem that was commented in https://github.com/ContaAzul/creditcard.js/issues/34.

    How we can solve that?

    Tasks:

    Automatically update release in:

    • [ ] NPM
    • [ ] Bower
    • [ ] Github release
    help wanted 
    opened by matheuspoleza 5
  • Improve security code check

    Improve security code check

    Using anchors in the regex, you can avoid partial matches (the old regex would match foo1234bar) and in this case, restrict the match to a fixed number of digits, making the code.length test redundant.

    opened by aureliojargas 4
  • Melhorias nos nomes das funções.

    Melhorias nos nomes das funções.

    refs #15

    • Renomeada funções.
    • Alterada função getCreditCardNameByNumber para retornar sempre String, quando o cartão não é válido irá retornar uma string 'Credit card is invalid!
    • Ajustado readme.

    @fernahh @matheuspoleza @ContaAzul/domphysis

    opened by pedrofurst 4
  • Add improvements for npm build

    Add improvements for npm build

    • Exult travis manifest;
    • Remove grunt, grunt-cli and grunt-contrib-clean;

    Fix build:clean task with rimraf and add -p param on mkdir to fix error on build.

    • Update author on .banner.
    opened by fernahh 4
  • Bump semver-regex from 3.1.2 to 3.1.3

    Bump semver-regex from 3.1.2 to 3.1.3

    Bumps semver-regex from 3.1.2 to 3.1.3.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 3
  • Add card options to isValid

    Add card options to isValid

    Want to request a feature or report a bug? I'd like to request a feature to add an options parameter to isValid function where it will be possible to specify which cards I'd like to verify. This comes in handy when my payment gateway doesn't support all supported cards and I just want to check with those that work for me. Does that make sense? Is it possible?

    What is the current behavior?

    isValid('4916108926268679'); // returns true
    

    What is the expected behavior?

    isValid('4916108926268679', { cards: ['visa', 'mastercard'] }) // returns true
    
    isValid('4916108926268679', { cards: ['mastercard'] }) // returns false
    
    enhancement 
    opened by diogomqbm 3
  • Apply more functional concepts in this library

    Apply more functional concepts in this library

    As you suggest @fernahh I'm replicating my coments from https://github.com/ContaAzul/creditcard.js/pull/78 here.

    I think https://github.com/ContaAzul/creditcard.js/pull/78 is a good start point for turning this library more functional.

    As an improvement, but not really required I also suggest applying more funcional concepts like decomposing some functions in smaller ones with less responsibilities.

    For example isSecurityCodeValid:

    export function isSecurityCodeValid(number, code) {
      let brand = getCreditCardNameByNumber(number);
      let numberLength;
    
      numberLength = (brand === 'Amex') ? 4 : 3;
      let regex = new RegExp(`^[0-9]{${numberLength}}$`);
    
      return regex.test(code);
    }
    

    could be refactored to something like:

    
    const isSecurityCodeValid = (number, code) =>
      isCodeLengthValid(code, getBrandCodeLength(getBrand(number)));
    

    or using some simple functional helpers like compose and curry for better readability:

    const isSecurityCodeValid = (number, code) =>
      compose(curry(isCodeLengthValid)(code), getBrandCodeLength, getBrand)(number);
    

    Another example isExpirationDateValid:

    export function isExpirationDateValid(paramMonth, paramYearn) {
      const month = parseInt(paramMonth, 10);
      const year = parseInt(paramYearn, 10);
    
      const currentYear = new Date().getFullYear();
      const currentMonth = new Date().getMonth() + 1;
    
      if (isNaN(month) || isNaN(year))
        return false;
    
      if (year === currentYear && month < currentMonth)
        return false;
    
      if (month < 1 || month > 12)
        return false;
    
      return !(year < 1000 || year >= 3000);
    }
    

    could be:

    export const isExpirationDateValid = (month, year) => 
      isValidMonth(month) && isValidYear(year) && !isPastDate(new Date(year, month));
    
    enhancement question 
    opened by carlosrberto 3
  • Validação de ano com restrições redundantes

    Validação de ano com restrições redundantes

    Basicamente a antiga validação verificava se o length do ano informado era inferior a 2 ou superior a 4 ou seja isso restringia o length data especificada em 2,3,4, vide bloco abaixo:

    if (yearLength < 2 && yearLength > 4)
    

    Considerando que qualquer ano com data inferior a 1000 e superior a 3000 vai retornar false por causa da validação abaixo:

    return !(y < 1000 || y >= 3000);
    

    Os seguintes exemplos de parâmetros inválidos passariam por todo o processamento do método até serem restringidos na última validação:

    "10", length = 2 // Qualquer outro número com length 2 também apresentaria o mesmo problema "200", length = 3 // Qualquer outro número com length 3 também apresentaria o mesmo problema

    Teríamos o custo de dar cast nos dados e proceder com as demais validações porque a primeira não está restringindo os dados em conjunto com as demais validações.

    opened by felipeuntill 3
  • fix: fixing isValid method

    fix: fixing isValid method

    What is the change?

    Fix isValid method when an invalid card number is passed with a valid checksum

    Why make this change?

    In order to fix this issue: https://github.com/ContaAzul/creditcard.js/issues/139

    Test plan

    opened by davidalves1 0
  • Please Reffer Fork Original

    Please Reffer Fork Original

    Please, i check this initial commit and is clear derivated from bin-cc project

    https://github.com/ContaAzul/creditcard.js/commit/10048883ff62b208c1b20f84a6052b6b1e0cb6cf

    https://github.com/renatovico/bin-cc/blob/master/creditcard-identifier.js

    opened by renatovico 0
Releases(v3.0.23)
Credit Card Issuance System with Sudo.Africa

sudo-creditcard Credit Card Issuance System with Sudo.Africa Project Structure Client - Frontend (Vue JS) src assets compponents router service (api r

Shamsuddeen Omacy 1 Feb 6, 2022
Lightweight JavaScript form validation library inspired by CodeIgniter.

validate.js validate.js is a lightweight JavaScript form validation library inspired by CodeIgniter. Features Validate form fields from over a dozen r

Rick Harrison 2.6k Dec 15, 2022
v8n ☑️ ultimate JavaScript validation library

The ultimate JavaScript validation library you've ever needed. Dead simple fluent API. Customizable. Reusable. Installation - Documentation - API Intr

Bruno C. Couto 4.1k Dec 30, 2022
Dead simple Object schema validation

Yup Yup is a JavaScript schema builder for value parsing and validation. Define a schema, transform a value to match, validate the shape of an existin

Jason Quense 19.2k Jan 2, 2023
Simple, smart and pleasant validation solution.

nice-validator Simple, smart and pleasant validation solution. Download the latest release or install package via npm or bower $ npm install nice-vali

Jony 608 Nov 18, 2022
jQuery Validation Plugin library sources

jQuery Validation Plugin - Form validation made easy The jQuery Validation Plugin provides drop-in validation for your existing forms, while making al

null 10.3k Jan 3, 2023
jQuery Validation Plugin library sources

jQuery Validation Plugin - Form validation made easy The jQuery Validation Plugin provides drop-in validation for your existing forms, while making al

null 10.3k Jan 3, 2023
The most powerful data validation library for JS

joi The most powerful schema description language and data validator for JavaScript. Installation npm install joi Visit the joi.dev Developer Portal f

Sideway Inc. 19.6k Jan 4, 2023
Lightweight and powerfull library for declarative form validation

Formurai is a lightweight and powerfull library for declarative form validation Features Setup Usage Options Methods Rules Examples Roadmap Features ?

Illia 49 May 13, 2022
A lightweight NodeJS library for strict mime-type validation on streams

A lightweight NodeJS library for strict mime-type validation on streams. It gets a ReadableStream and decets the mime-type using its Magic number and validates it using the provided allowed and forbidden lists; If it's allowed it will pass it to the created WritableStreams and if it's not it will throw an error.

CEO of Death Star 9 Apr 3, 2022
Themis is a validation and processing library that helps you always make sure your data is correct.

Dataffy Themis - The advanced validation library Themis is a validation and processing library that helps you always make sure your data is correct. ·

Dataffy 14 Oct 27, 2022
:white_check_mark: Easy property validation for JavaScript, Node and Express.

property-validator ✅ Easy property validation for JavaScript, Node and Express Built on top of validator.js, property-validator makes validating reque

Netto Farah 160 Dec 14, 2022
String validation

validator.js A library of string validators and sanitizers. Strings only This library validates and sanitizes strings only. If you're not sure if your

null 20.7k Jan 5, 2023
Cross Browser HTML5 Form Validation.

Validatr Cross Browser HTML5 Form Validation. Getting Started View the documentation to learn how to use Validatr. Changelog Version 0.5.1 - 2013-03-1

Jay Morrow 279 Nov 1, 2022
jQuery form validation plugin

jQuery.validationEngine v3.1.0 Looking for official contributors This project has now been going on for more than 7 years, right now I only maintain t

Cedric Dugas 2.6k Dec 23, 2022
Schema-Inspector is an JSON API sanitisation and validation module.

Schema-Inspector is a powerful tool to sanitize and validate JS objects. It's designed to work both client-side and server-side and to be scalable wit

null 494 Oct 3, 2022
Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

upjs 314 Dec 26, 2022
📫 Offline email validation - JS or TS

email-seems-valid An offline check to see if an email seems valid. Contains TS or JS packages for browser or Node.js emailSeemsValid('[email protected]')

earnifi 12 Dec 25, 2022