Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Credit card detection jquery plugin. Saving from permanent deletion.
/**
* Card Detective jQuery Plugin
*
* Author : Tyler Childs
* Email : tylerwchilds@gmail.com
*
* Purpose : Automatically detect a credit card value based on user input
*
* Usage :
*
* $( selector ).CardDetective();
* Ex. $("#card_number").CardDetective();
*
*
*
* Options :
*
* {
* detected: function, // function that will fire when card type has changed
* cards: $( selector ), // selectors that will be toggled active/inactive
* tests: [ { regex, string }] // array of objects with regular expression and card type string.
* }
*
*
*
*/
(function ( $ ) {
$.fn.CardDetective = function( options ) {
var settings = $.extend({
detected: cardChanged,
cards: $('.card-image'),
tests: [
{
regex: new RegExp("^5[1-5]"),
type: "mastercard"
},
{
regex: new RegExp("^4"),
type: "visa"
},
{
regex: new RegExp("^3[47]"),
type: "amex"
},
{
regex: new RegExp("^6(?:011|5)"),
type: "discover"
}
]
}, options );
function getCreditCardType( event ) {
var $this = event.data.elem;
var accountNumber = $this.val();
var type = $this.data("type");
$this.data("type", "unknown");
for(var i = 0; i < settings.tests.length; i++){
if (settings.tests[i].regex.test(accountNumber)){
$this.data("type", settings.tests[i].type);
break;
}
}
// Card Updated
if( $this.data("type") != type ){
// fire event and pass in the card type
$( window ).trigger( "card-detected", [ $this.data("type") ] );
}
}
function cardChanged( event, type ){
var $cards = event.data.cards;
if(type === "unknown"){
$cards.removeClass('inactive active');
} else {
$cards.addClass('inactive');
$('.'+ type).toggleClass('inactive active');
}
var cvv_length = type === "amex" ? 4 : 3;
$cvv = $("input[name='cvv2']");
$cvv.rules("remove", "minlength maxlength");
$cvv.rules("add", { minlength: cvv_length, maxlength: cvv_length});
}
this.each(function() {
$(this).on('keyup', { elem: $(this), test: 'string' }, getCreditCardType).data("type", "unknown");
$( window ).on('card-detected', { cards: settings.cards }, settings.detected);
});
return this;
};
}( jQuery ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment