creditCard validator

Validate a credit card number

Options

Using with form field
The HTML attributes are used to set the validator options via the Declarative plugin
NameHTML attributeTypeDescription
messagedata-fv-credit-card___messageStringThe error message
Behind the scene, in addition to using the Luhn algorithm, the validator also validate the IIN ranges and length of credit card number.
It supports validating the following cards:
TypeSample
American Express340653705597107
Dankort5019717010103742
Diners Club30130708434187
Diners Club (US)5517479515603901
Discover6011734674929094
Elo6362970000457013
JCB3566002020360505
Laser6304 9000 1774 0292 441
Maestro6762835098779303
Mastercard5303765013600904
Solo6334580500000000
Visa4929248980295542
Visa Electron4917300800000000
13 digits Visa credit cards are no longer used and it will be treated as an invalid card number
Using the ES6 module
// You might need to change the importing path
import { creditCard } from '/vendors/@form-validation/cjs/validator-credit-card';
const result = creditCard().validate({
value: ...,
options: {
message: ...,
},
});
/*
result is an object of
{
valid: true or false,
message: The error message,
meta: {
// The type of credit card
// Can be null or one of AMERICAN_EXPRESS, DINERS_CLUB, DINERS_CLUB_US, DISCOVER, JCB, LASER,
// MAESTRO, MASTERCARD, SOLO, UNIONPAY, VISA
type: ...
}
}
*/
Using the npm package
  • Install the validator package:
$ npm install @form-validation/validator-credit-card
  • Use the creditCard validator:
import { creditCard } from '@form-validation/validator-credit-card';
const result = creditCard().validate({
value: ...,
options: {
message: ...,
},
});

Basic example

creditCard validator

NPM package example

The following snippet shows how to use the creditCard validator with the npm package:
import { creditCard } from '@form-validation/validator-credit-card';
const res1 = creditCard().validate({
value: '340653705597107',
options: {
message: 'The credit card number is not valid',
},
});
// res1.valid === true
// res1.meta.type === 'AMERICAN_EXPRESS'
const res2 = creditCard().validate({
value: '5303765013600',
options: {
message: 'The credit card number is not valid',
},
});
// res2.valid === false
// res2.meta.type === null

See also

Changelog

v2.0.0
  • Add the npm package