Credit Card Validator and Type Predictor
Version 2.0.0 Released May 2, 2013
Why Would You Use CardCheck?
CardCheck is a credit card validator and type predictor. It provides a stand-alone script along with a jQuery plugin compatible with jQuery versions 1.9.1 and 2.0.0. Why do you need it? It saves your customers time by instantly telling them of errors in card entry as well as saving them the step of choosing their card type themselves.
Version 2.0.0 - Changelog
- Added Maestro Card Support.
- Added testing using qUnit.
- Updated Plugin for jQuery 1.9.1 and 2.0.0. Either will work fine.
- Separated out the core functionality and exposed it at CardCheck() to enable your own implementation
- Added ability to manually fire card evaluation
- Added ability to access internal processing object of element
- Fixed a number of bugs and edge cases
- Support multiple instances of the plugin
- Broadcast internal events using custom jQuery events on the element ( "cc:EVENT" }
- There are now three unique ways to setup callbacks.
Buy on CodeCanyon
Need Custom Integration?
Demo Type a credit card number from below. Supports multiple instances
Credit Card Inputs
Credit Card Numbers for Demo
Enter each card number into the demo above to see it work!
Type | Number |
---|---|
Visa | 4012 8888 8888 1881 |
MasterCard | 5105 1051 0510 5100 |
Amex | 3714 496353 98431 |
Discover | 6011 0009 9013 9424 |
Diners Club | 3056 93090 25904 |
JCB | 3566 0020 2036 0505 |
Maestro | 6759 6498 2643 8453 |
Installation
Upload the "images" and "js" directory into your site.
Link to the location of your cardcheck plugin. You should use the minified version in production.
<script src="js/cardcheck.min.js" type="text/javascript"></script>Reminder: Upload Image Directory for the icons
Don't forget to upload the images to your server. The directory included with cardcheck.js includes the folder called "images" that contains the default credit card type icons you see in the demo (Visa, Mastercard, etc). You can easily replace these icons with any other ones that you may have. The sizes do not matter, just the naming scheme.
Usage Instructions
Basic Initialization
You can get off the ground running without having to pass any settings. Although CardCheck is highly configurable, you do not have to be a javascript expert to use this plugin.
$(document).ready(function() { $('#credit-card').cardcheck(); });
Initialization With Custom Settings
Card Check is highly configurable so that you can adjust most of the functionality. Here is an example of how to initialize Card Check with some settings. Learn more in the API Settings section.
$(document).ready(function() { $('#credit-card').cardcheck({ iconLocation: '#accepted-cards-images', allowSpaces: false }); });
Alternate Methods for Initializing Card Check
Pass an input directly to cardcheck.js as the first parameter. Learn more in the API Settings section.
$(document).ready(function() { // Method #1 via jQuery Selector $('#credit-card').cardcheck({ iconLocation: '#accepted-cards-images' }); // Method #2 - first param = element, second param = options $.cardcheck('#credit-card', { iconLocation: '#accepted-cards-images' }); // Method #3 first param defines element through input option along with other options, Second param ignored $.cardcheck({ input: '#credit-card', iconLocation: '#accepted-cards-images' }); });
Chainable
Chain additional jQuery methods after initializing cardcheck.js.
$.cardcheck('#credit-card').addClass('myclass');
StandAlone NEW
You control the entire implementation. Copy the code below and paste it in your console.
var myCard = CardCheck({ allowSpaces: false }); myCard.onValid(function(card) { alert(card + ' is valid'); }); myCard.cardNumber('4012888888881881');
You can access the internal instance of the CardCheck object by doing the following:
var myCard = $('#credit-card').cardcheck().cardcheck('instance'); // This allows you to chain as many callbacks as you want myCard.onValid(function(card) { console.log('callback1'); }).onValid(function(card) { console.log('callback2'); });
Manually Fire Evaluation NEW
There may be some edge cases where the plugin does not fire automatically. On these cases we allow you to manually call the evaluation method on an instantiated cardcheck element. This example should NOT be implemented, but proves the flexibility of the plugin.
var creditCard = $('#credit-card2'); creditCard.on('cc:onValid', function(event, card) { console.log(card); }).cardcheck(); // Don't manually manipulate the internal instance properties // You can... but there is probably a better way to achieve what you want. var instance = creditCard.cardcheck('instance'); instance._cardNumber = '4012888888881881'; creditCard.cardcheck('evaluate');
API Callbacks Listen for Seven Unique Callbacks
NEW Every event will be broadcasted to a custom event listener on the element. What does that mean? Let me show you:
// Demo #2 above is running this right now. Check your console after you paste a valid credit card in. var creditCard = $('#credit-card2'); creditCard.on('cc:onValid', function(event, card) { console.log(card); }).cardcheck(); // This code is equivalent to the following creditCard.cardcheck({ onValid: function(card) { console.log(card); } })The benefit of broadcasting the events is that you can bind as many callbacks on a single event as you want and do it before initialization.
Callback Details
Available Callbacks: "onToggle", "onValid", "onValidation", "onInvalid", "onError", "onUnknown", "onGuess", "onReset", "onCardChange", "onTypeUpdate"
Key | Default Value | Description |
---|---|---|
onToggle | function(isValid, card, niceName) {} |
This is called anytime a change occurs to the state of the instance. "isValid" can be null, true, or false. "card" will be a string (e.g. "visa") or null.
// Both of these register the callback. $('#credit-card').on('cc:onToggle', function(event, isValid, card, niceName) {}); $('#credit-card').cardcheck({ onToggle: function(isValid, card, niceName) {} }); |
onValid | function(card, niceName) {} |
Anytime a complete match is found and the luhn check has been performed.
// Both of these register the callback. $('#credit-card').on('cc:onValid', function(event, card, niceName) {}); $('#credit-card').cardcheck({ onValid: function(card, niceName) {} }); |
onInvalid | function() {} |
Anytime an error occurs. Could be a non-numeric entry or a number longer than allowed.
// Both of these register the callback. $('#credit-card').on('cc:onInvalid', function(event) {}); $('#credit-card').cardcheck({ onInvalid: function() {} }); |
onUnknown | function(card, niceName) {} |
In this function there is not enough information to know for sure that the card is valid. However, if "card" is not null, that means that we have a pretty good guess at what the card will be.
// Both of these register the callback. $('#credit-card').on('cc:onUnknown', function(event, card, niceName) {}); $('#credit-card').cardcheck({ onUnknown: function(card, niceName) {} }); |
onGuess | function(card, niceName) {} |
This is a subset of "onUnkown" but only fires when we are confident of the type of card it will most likely be.
// Both of these register the callback. $('#credit-card').on('cc:onGuess', function(event, card, niceName) {}); $('#credit-card').cardcheck({ onGuess: function(card, niceName) {} }); |
onReset | function() {} |
This manages reseting the input to a non-success or non-error state. This function accepts no parameters. This will be called anytime the card was validated and is no longer valid but is not in error either. It will also be called when invalid characters were entered and have subsequently been removed. // Both of these register the callback. $('#credit-card').on('cc:onReset', function(event) {}); $('#credit-card').cardcheck({ onReset: function() {} }); |
onCardChange | function(card, niceName) {} |
Anytime the type of the card changes, this method will be called. It will be called even if the type of the card changes from a known card, such as "visa", to unknown, which is represented by null.
// Both of these register the callback. $('#credit-card').on('cc:onCardChange', function(event, card, niceName) {}); $('#credit-card').cardcheck({ onCardChange: function(card, niceName) {} }); |
onError DEPRECATED |
function( card ){} |
Use "onInvalid" instead. This is called anytime that an error occurs. This will normally return the actual type, unless the error is because the value entered is not a number.
$('#credit-card').cardcheck({ onError: function( type ) { // Notify user the number is valid alert('Credit Card Type Not Valid: ' + type ); } }); |
onValidation DEPRECATED |
function( card, niceName ){} |
Use "onValid" instead. Callback function that is called if validation is true. You can use this to hook into a notification plugin or your own custom code.
$('#credit-card').cardcheck({ onValidation: function( type, niceName ) { // Notify user the number is valid alert('Valid Credit Card Number! ' + niceName); } }); |
onTypeUpdate DEPRECATED |
function( card, niceName ){} |
Use "onCardChange" instead. Callback function that is called each time the type of credit card changes.
$('#credit-card').cardcheck({ onTypeUpdate: function( type, niceName ) { // Do something on keyup and/or change alert('The credit card type has changed! ' + niceName); } }); |
API Settings Configuration Options for CardCheck
Key | Default Value | Description |
---|---|---|
acceptedCards |
acceptedCards: [ 'visa', 'mastercard', 'amex', 'discover', 'diners', 'jcb', 'maestro' ] |
Add or remove items from this list to change the accepted card types. Currently, cardcheck.js only supports the seven major credit cards listed.
This example only accepts Visa and MasterCard. $('#credit-card').cardcheck({ acceptedCards: [ 'visa', 'mastercard' ] });Important You cannot deviate from the naming scheme: [visa','mastercard','amex','diners','discover','jcb', 'maestro'] |
allowSpaces | true |
This controls whether validation will fail or pass if spaces are entered to separate number blocks. For example, "4111 1111 1111 1111" would be a valid Visa card if this option is enabled.
Important Since this is enabled by default, you should probably have something on the backend that removes any spaces from the credit card field. Otherwise, it may fail when you submit it to your payment processor. <?php // Here are two example in PHP for how to accomplish this $credit_card = '4111 1111 1111 1111'; // Simple string replace echo str_replace(' ', '', $credit_card); // Outputs: 4111111111111111 // String replace with preg_replace echo preg_replace('/\s+/', '', $credit_card); // Outputs: 4111111111111111 ?> |
enableIcons | true |
Set to true or false to display the credit card icons. If false, the icons will not be appended and you'll be left to use the callbacks alone.
$('#credit-card').cardcheck({ enableIcons: false }); JS Tip Ensure you do not have trailing commas in your code. Trailing commas may cause errors in older browsers. For example, do not add a comma after enableIcons: false in this example. |
iconLocation |
Change this value if you want your icons to be appended somewhere different. By default they will append to the parent element that houses your input. (e.g. They will be siblings) However it may be easier to control by just setting a specific element like we do in the demo { iconLocation: '#accepted-cards-images' } Check out how we use this in the demo |
|
iconDir | images/ |
Change this value if you want your icons to be located somewhere different. This allows you to store your images on a CDN or somewhere besides the root domain. Important You must include the trailing slash. If you want to define an absolute path, include the full URL like this: { iconDir: "http://www.example.com/images/" } You can also use a directory relative to the script like this: { iconDir: "images/" } |
iconExt | png | Change this value if you want to use custom icons with a different extension. |
input | undefined |
Initialize cardcheck.js on this input. This provides an optional way to initialize cardcheck.js.
$.cardcheck({ input: '#credit-card' }); |
Additional Settings Adding Card Types
There are a couple additional settings that are not included above as they involve advanced configuration of the plugin. They really should only need to be edited if one is adding additional credit card types. The uncompressed source code is fairly well documented to support you in this and the actual options are as follows: niceNames, regExpNumCheck, regExpApprox, startNum, and cardLength. Get in touch if you're looking to add a credit card type and we'll assist you in crafting the proper settings.
Demo Code
This is the HTML and scripts used in the demo above. The classes you see here (control-group, controls, pull-left, etc.) are used with Twitter's Bootstrap v2.3.1 CSS.
<!-- Credit Card Number Input --> <div class="control-group"> <label class="control-label" for="credit-card"><strong>Card Number</strong></label> <div class="controls"> <input class="xlarge" id="credit-card" name="credit-card" type="text"> <span id="credit-card-type-text" class="help-inline"></span> </div> </div> <!-- Card Images Output --> <div class="control-group"> <label>Accepted Cards</label> <div class="controls"> <div class="pull-left" id="accepted-cards-images"> <!-- Icons Automatically Inserted Here --> </div> </div> </div> <!-- Script to control the card input --> <script type="text/javascript"> // Make sure that this code goes within a doc ready $(document).ready(function() { // Step #1: Cache Selectors var creditCard = $("#credit-card"), cardGrandParent = creditCard.parent().parent(); // Step #2: Setup Callbacks on Events creditCard.on("cc:onReset cc:onGuess", function() { cardGrandParent.removeClass().addClass("control-group"); }).on("cc:onInvalid", function() { cardGrandParent.removeClass().addClass("control-group error"); $("#credit-card-type-text").text(""); }).on("cc:onValid", function(event, card, niceName) { cardGrandParent.removeClass().addClass("control-group success"); }).on("cc:onCardChange", function(event, card, niceName) { $("#credit-card-type-text").text(niceName); // Step #3: Initialize the cardcheck plugin }).cardcheck({ iconLocation: "#accepted-cards-images" }); }); </script>
Tests Full test coverage by qUnit
Testing ensures the stability of the internals of the stand-alone script. The jQuery plugin is only adding a listener to the core and providing card images. View the tests