Skip to content

Instantly share code, notes, and snippets.

@madrobby
Forked from 140bytes/LICENSE.txt
Created May 18, 2011 13:50
Show Gist options
  • Save madrobby/978597 to your computer and use it in GitHub Desktop.
Save madrobby/978597 to your computer and use it in GitHub Desktop.
Credit card detection

Returns the type of credit card for a given number (as string), recognizing Visa, MasterCard and American Express cards (data object can be easily extended with more card types!).

var whichCard = function(a,b,c){b={v:/^4\d{12}(?:\d{3})?$/,m:/^5[1-5]\d{14}$/,a:/^3[47]\d{13}$/};for(c in b)if(b[c].exec(a))return c};

whichCard('4111111111111111') // => 'v' (visa)
function(
a, // credit card number (string)
b, // placeholder
c // placeholder
) {
b = { // data object
v: /^4\d{12}(?:\d{3})?$/, // regexp for visa
m: /^5[1-5]\d{14}$/, // regexp for mastercard
a: /^3[47]\d{13}$/ // regexp for american express
};
for (c in b) // for each card regexp
if (b[c].exec(a)) // check if the number matches
return c // if so, return the card type
}
function(a,b,c){b={v:/^4\d{12}(?:\d{3})?$/,m:/^5[1-5]\d{14}$/,a:/^3[47]\d{13}$/};for(c in b)if(b[c].exec(a))return c}
Copyright (c) 2011 Thomas Fuchs, http://mir.aculo.us/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
"name": "creditcard_type",
"description": "Returns the type of credit card for a given card number",
"keywords": [
"creditcard",
"form"
]
}
@chrisevans
Copy link

Wouldn't adding a +"" inside the exec force the input to a string? still 120 bytes
function(a,b,c){b={v:/^4\d{12}(?:\d{3})?$/,m:/^5[1-5]\d{14}$/,a:/^3[47]\d{13}$/};for(c in b)if(b[c].exec(a+""))return c}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment