How to check your credit card number

I just want to check the credit card number in javascript, I used a regular expression for numbers, but I don't know why this does not work !!! here is my function as below:

function validate_creditcardnumber() { var re16digit=/^\d{16}$/ if (document.myform.CreditCardNumber.value.search(re16digit)==-1) alert("Please enter your 16 digit credit card numbers"); return false; } 

Any help would be appreciated

+7
source share
13 answers

Hope the following two links help solve your problem. FYI, various credit cards are available in the world. So yours, although it is mistaken, credit cards have a certain format. See the following links. The first is pure Javascript, and the second is jQuery.

http://www.braemoor.co.uk/software/creditcard.shtml

https://github.com/iHwy/jQuery-Validation-Extension

+9
source

You can use this snippet to check card numbers for 16 digits using the Luhn algorithm :

 function validateCardNumber(number) { var regex = new RegExp("^[0-9]{16}$"); if (!regex.test(number)) return false; return luhnCheck(number); } function luhnCheck(val) { var sum = 0; for (var i = 0; i < val.length; i++) { var intVal = parseInt(val.substr(i, 1)); if (i % 2 == 0) { intVal *= 2; if (intVal > 9) { intVal = 1 + (intVal % 10); } } sum += intVal; } return (sum % 10) == 0; } 
+9
source

A credit card number is not a bunch of random numbers. There is a validation form.

After a quick google, I found this javascript that will check the credit card number to be valid.

http://javascript.internet.com/forms/credit-card-number-validation.html

Broken URL: Internet archieve: http://web.archive.org/web/20100129174150/http://javascript.internet.com/forms/credit-card-number-validation.html?

 <!-- TWO STEPS TO INSTALL CREDIT CARD NUMBER VALIDATION: 1. Copy the coding into the HEAD of your HTML document 2. Add the last code into the BODY of your HTML document --> <!-- STEP ONE: Paste this code into the HEAD of your HTML document --> <HEAD> <script type="text/javascript"> <!-- /* This script and many more are available free online at The JavaScript Source!! http://javascript.internet.com Created by: David Leppek :: https://www.azcode.com/Mod10 Basically, the alorithum takes each digit, from right to left and muliplies each second digit by two. If the multiple is two-digits long (ie: 6 * 2 = 12) the two digits of the multiple are then added together for a new number (1 + 2 = 3). You then add up the string of numbers, both unaltered and new values and get a total sum. This sum is then divided by 10 and the remainder should be zero if it is a valid credit card. Hense the name Mod 10 or Modulus 10. */ function Mod10(ccNumb) { // v2.0 var valid = "0123456789" // Valid digits in a credit card number var len = ccNumb.length; // The length of the submitted cc number var iCCN = parseInt(ccNumb); // integer of ccNumb var sCCN = ccNumb.toString(); // string of ccNumb sCCN = sCCN.replace (/^\s+|\s+$/g,''); // strip spaces var iTotal = 0; // integer total set at zero var bNum = true; // by default assume it is a number var bResult = false; // by default assume it is NOT a valid cc var temp; // temp variable for parsing string var calc; // used for calculation of each digit // Determine if the ccNumb is in fact all numbers for (var j=0; j<len; j++) { temp = "" + sCCN.substring(j, j+1); if (valid.indexOf(temp) == "-1"){bNum = false;} } // if it is NOT a number, you can either alert to the fact, or just pass a failure if(!bNum){ /*alert("Not a Number");*/bResult = false; } // Determine if it is the proper length if((len == 0)&&(bResult)){ // nothing, field is blank AND passed above # check bResult = false; } else{ // ccNumb is a number and the proper length - let see if it is a valid card number if(len >= 15){ // 15 or 16 for Amex or V/MC for(var i=len;i>0;i--){ // LOOP throught the digits of the card calc = parseInt(iCCN) % 10; // right most digit calc = parseInt(calc); // assure it is an integer iTotal += calc; // running total of the card number as we loop - Do Nothing to first digit i--; // decrement the count - move to the next digit in the card iCCN = iCCN / 10; // subtracts right most digit from ccNumb calc = parseInt(iCCN) % 10 ; // NEXT right most digit calc = calc *2; // multiply the digit by two // Instead of some screwy method of converting 16 to a string and then parsing 1 and 6 and then adding them to make 7, // I use a simple switch statement to change the value of calc2 to 7 if 16 is the multiple. switch(calc){ case 10: calc = 1; break; //5*2=10 & 1+0 = 1 case 12: calc = 3; break; //6*2=12 & 1+2 = 3 case 14: calc = 5; break; //7*2=14 & 1+4 = 5 case 16: calc = 7; break; //8*2=16 & 1+6 = 7 case 18: calc = 9; break; //9*2=18 & 1+8 = 9 default: calc = calc; //4*2= 8 & 8 = 8 -same for all lower numbers } iCCN = iCCN / 10; // subtracts right most digit from ccNum iTotal += calc; // running total of the card number as we loop } // END OF LOOP if ((iTotal%10)==0){ // check to see if the sum Mod 10 is zero bResult = true; // This IS (or could be) a valid credit card number. } else { bResult = false; // This could NOT be a valid credit card number } } } // change alert to on-page display or other indication as needed. if(bResult) { alert("This IS a valid Credit Card Number!"); } if(!bResult){ alert("This is NOT a valid Credit Card Number!"); } return bResult; // Return the results } // --> </script> </HEAD> <!-- STEP TWO: Copy this code into the BODY of your HTML document --> <BODY> <div align="center"> <form name="Form1"> <table width="50%" border="0" cellspacing="0" cellpadding="5"> <tr> <td width="50%" align="right">Credit Card Number:   </td> <td width="50%"> <input name="CreditCard" type="text" value="4012888888881881" size="18" maxlength="16" style="border: 1px solid #000098; padding: 3px;"> </td> </tr> <tr> <td colspan="2" align="center"> <input type="button" name="Button" style="color: #fff; background: #000098; font-weight:bold; border: solid 1px #000;" value="TEST CARD NUMBER" onClick="return Mod10(document.Form1.CreditCard.value);"> </td> </tr> </table> </form> </div> <p><center> <font face="arial, helvetica" size"-2">Free JavaScripts provided<br> by <a href="http://javascriptsource.com">The JavaScript Source</a></font> </center><p> <!-- Script Size: 4.97 KB --> 
+6
source

You define the variable name re16digit , but you later refer to it as re10digit , which throws an error. To simplify the code, you should use RegExp.prototype.test() , not String.prototype.search() :

 function validate_creditcardnumber() { var re16digit = /^\d{16}$/; if (!re16digit.test(document.myform.CreditCardNumber.value)) { alert("Please enter your 16 digit credit card numbers"); return false; } } 

Working demo: http://jsfiddle.net/Dxjkh/

As already mentioned, you might be better off using Luhn's JavaScript implementation of the algorithm . It is also worth noting that a 16-digit check will not be performed for American Express (15-digit) and Diners (14-digit) cards.

+4
source

The Moon algorithm is used to add validation of credit and debit card numbers. This Javascript function should work.

 function validate_creditcardnumber(inputNum) { var digit, digits, flag, sum, _i, _len; flag = true; sum = 0; digits = (inputNum + '').split('').reverse(); for (_i = 0, _len = digits.length; _i < _len; _i++) { digit = digits[_i]; digit = parseInt(digit, 10); if ((flag = !flag)) { digit *= 2; } if (digit > 9) { digit -= 9; } sum += digit; } return sum % 10 === 0; }; 
+4
source

You really should use .test() :

 if (!re16digit.test(document.myform.CreditCardNumber.value)) { alert("Please ... "); } 

You should also examine implementations of (one or more) card number checksum algorithms. They are very simple.

+3
source

http://www.w3resource.com/javascript/form/credit-card-validation.php + Moon algorithm:

 var checkLuhn = function (cardNo) { var s = 0; var doubleDigit = false; for (var i = cardNo.length - 1; i >= 0; i--) { var digit = +cardNo[i]; if (doubleDigit) { digit *= 2; if (digit > 9) digit -= 9; } s += digit; doubleDigit = !doubleDigit; } return s % 10 == 0; } 

PS Do not use regex for this, as is done by reference. But it is useful to use the textual definitions of each map. Here he is:

American Express: - Starting at 34 or 37, 15 digits long.

Visa: - Starting with 4, 13 or 16 digits long.

MasterCard: - Starting from 51 to 55, the length is 16 digits.

Discover: - Starting with 6011, 16 digits long or starting with 5, 15 digits long.

Diners Club: - Starting from 300 to 305, 36 or 38, with a length of 14 digits.

JCB: - Starting with 2131 or 1800, 15 digits long, or starting with 35, 16 digits long.

I did it as follows:

 var validateCardNo = function (no) { return (no && checkLuhn(no) && no.length == 16 && (no[0] == 4 || no[0] == 5 && no[1] >= 1 && no[1] <= 5 || (no.indexOf("6011") == 0 || no.indexOf("65") == 0)) || no.length == 15 && (no.indexOf("34") == 0 || no.indexOf("37") == 0) || no.length == 13 && no[0] == 4) } 
+3
source

Perhaps you should look here: http://en.wikipedia.org/wiki/Luhn_algorithm

Here is a java snippet that checks for a credit card number that should be simple enough to convert to javascript:

  public static boolean isValidCC(String number) { final int[][] sumTable = {{0,1,2,3,4,5,6,7,8,9},{0,2,4,6,8,1,3,5,7,9}}; int sum = 0, flip = 0; for (int i = number.length() - 1; i >= 0; i--) { sum += sumTable[flip++ & 0x1][Character.digit(number.charAt(i), 10)]; } return sum % 10 == 0; } 
+2
source

This works: http://jsfiddle.net/WHKeK/

 function validate_creditcardnumber() { var re16digit=/^\d{16}$/ if (document.myform.CreditCardNumber.value.search(re16digit)==-1) alert("Please enter your 16 digit credit card numbers"); return false; } 

You have a typo. You call the re16digit variable, but in your search you have re10digit .

+1
source

I am sure that all of these algorithms are great, but you cannot verify that the card number is valid by simply running the algorithm on it. The algorithms make sure that the format is correct and its checksums are valid, but they do not guarantee that the bank will accept the card ... for this you need to actually transfer the card number to your bank for approval.

0
source

These are my 5 cents.
Please note that this is not an ideal verification method, but is suitable for my needs.

 function validateCCNum(ccnum) { var ccCheckRegExp = /[^\d\s-]/; var isValid = !ccCheckRegExp.test(ccnum); var i; if (isValid) { var cardNumbersOnly = ccnum.replace(/[\s-]/g,""); var cardNumberLength = cardNumbersOnly.length; var arrCheckTypes = ['visa', 'mastercard', 'amex', 'discover', 'dinners', 'jcb']; for(i=0; i<arrCheckTypes.length; i++) { var lengthIsValid = false; var prefixIsValid = false; var prefixRegExp; switch (arrCheckTypes[i]) { case "mastercard": lengthIsValid = (cardNumberLength === 16); prefixRegExp = /^5[1-5]/; break; case "visa": lengthIsValid = (cardNumberLength === 16 || cardNumberLength === 13); prefixRegExp = /^4/; break; case "amex": lengthIsValid = (cardNumberLength === 15); prefixRegExp = /^3([47])/; break; case "discover": lengthIsValid = (cardNumberLength === 15 || cardNumberLength === 16); prefixRegExp = /^(6011|5)/; break; case "dinners": lengthIsValid = (cardNumberLength === 14); prefixRegExp = /^(300|301|302|303|304|305|36|38)/; break; case "jcb": lengthIsValid = (cardNumberLength === 15 || cardNumberLength === 16); prefixRegExp = /^(2131|1800|35)/; break; default: prefixRegExp = /^$/; } prefixIsValid = prefixRegExp.test(cardNumbersOnly); isValid = prefixIsValid && lengthIsValid; // Check if we found a correct one if(isValid) { break; } } } if (!isValid) { return false; } // Remove all dashes for the checksum checks to eliminate negative numbers ccnum = ccnum.replace(/[\s-]/g,""); // Checksum ("Mod 10") // Add even digits in even length strings or odd digits in odd length strings. var checksum = 0; for (i = (2 - (ccnum.length % 2)); i <= ccnum.length; i += 2) { checksum += parseInt(ccnum.charAt(i - 1)); } // Analyze odd digits in even length strings or even digits in odd length strings. for (i = (ccnum.length % 2) + 1; i < ccnum.length; i += 2) { var digit = parseInt(ccnum.charAt(i - 1)) * 2; if (digit < 10) { checksum += digit; } else { checksum += (digit - 9); } } return (checksum % 10) === 0; } 
0
source
 This Code Works: function check_credit_card_validity_contact_bank(random_id) { var cb_visa_pattern = /^4/; var cb_mast_pattern = /^5[1-5]/; var cb_amex_pattern = /^3[47]/; var cb_disc_pattern = /^6(011|5|4[4-9]|22(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]))/; var credit_card_number = jQuery("#credit_card_number_text_field_"+random_id).val(); var cb_is_visa = cb_visa_pattern.test( credit_card_number ) === true; var cb_is_master = cb_mast_pattern.test( credit_card_number ) === true; var cb_is_amex = cb_amex_pattern.test( credit_card_number ) === true; var isDisc = cb_disc_pattern.test( credit_card_number ) === true; cb_is_amex ? jQuery("#credit_card_number_text_field_"+random_id).mask("999999999999999") : jQuery("#credit_card_number_text_field_"+random_id).mask("9999999999999999"); var credit_card_number = jQuery("#credit_card_number_text_field_"+random_id).val(); cb_is_amex ? jQuery("#credit_card_number_text_field_"+random_id).mask("9999 9999 9999 999") : jQuery("#credit_card_number_text_field_"+random_id).mask("9999 9999 9999 9999"); if( cb_is_visa || cb_is_master || cb_is_amex || isDisc) { if( cb_is_visa || cb_is_master || isDisc) { var sum = 0; for (var i = 0; i < credit_card_number.length; i++) { var intVal = parseInt(credit_card_number.substr(i, 1)); if (i % 2 == 0) { intVal *= 2; if (intVal > 9) { intVal = 1 + (intVal % 10); } } sum += intVal; } var contact_bank_check_validity = (sum % 10) == 0 ? true : false; } jQuery("#text_appear_after_counter_credit_card_"+random_id).css("display","none"); if( cb_is_visa && contact_bank_check_validity) { jQuery("#credit_card_number_text_field_"+random_id).css({"background-image":"url(<?php echo plugins_url("assets/global/img/cc-visa.svg", dirname(__FILE__)); ?>)","background-repeat":"no-repeat","padding-left":"40px", "padding-bottom":"5px"}); } else if( cb_is_master && contact_bank_check_validity) { jQuery("#credit_card_number_text_field_"+random_id).css({"background-image":"url(<?php echo plugins_url("assets/global/img/cc-mastercard.svg", dirname(__FILE__)); ?>)","background-repeat":"no-repeat","padding-left":"40px", "padding-bottom":"5px"}); } else if( cb_is_amex) { jQuery("#credit_card_number_text_field_"+random_id).unmask(); jQuery("#credit_card_number_text_field_"+random_id).mask("9999 9999 9999 999"); jQuery("#credit_card_number_text_field_"+random_id).css({"background-image":"url(<?php echo plugins_url("assets/global/img/cc-amex.svg", dirname(__FILE__)); ?>)","background-repeat":"no-repeat","padding-left":"40px","padding-bottom":"5px"}); } else if( isDisc && contact_bank_check_validity) { jQuery("#credit_card_number_text_field_"+random_id).css({"background-image":"url(<?php echo plugins_url("assets/global/img/cc-discover.svg", dirname(__FILE__)); ?>)","background-repeat":"no-repeat","padding-left":"40px","padding-bottom":"5px"}); } else { jQuery("#credit_card_number_text_field_"+random_id).css({"background-image":"url(<?php echo plugins_url("assets/global/img/credit-card.svg", dirname(__FILE__)); ?>)","background-repeat":"no-repeat","padding-left":"40px" ,"padding-bottom":"5px"}); jQuery("#text_appear_after_counter_credit_card_"+random_id).css("display","block").html(<?php echo json_encode($cb_invalid_card_number);?>).addClass("field_label"); } } else { jQuery("#credit_card_number_text_field_"+random_id).css({"background-image":"url(<?php echo plugins_url("assets/global/img/credit-card.svg", dirname(__FILE__)); ?>)","background-repeat":"no-repeat","padding-left":"40px" ,"padding-bottom":"5px"}); jQuery("#text_appear_after_counter_credit_card_"+random_id).css("display","block").html(<?php echo json_encode($cb_invalid_card_number);?>).addClass("field_label"); } } 
0
source

The same code as above, with better syntax.

 function Mod10(ccNumb) { var valid = "0123456789" // Valid digits in a credit card number var len = ccNumb.length; // The length of the submitted cc number var iCCN = parseInt(ccNumb); // integer of ccNumb var sCCN = ccNumb.toString(); // string of ccNumb sCCN = sCCN.replace (/^\s+|\s+$/g,''); // strip spaces var iTotal = 0; // integer total set at zero var bNum = true; // by default assume it is a number var bResult = false; // by default assume it is NOT a valid cc var temp; // temp variable for parsing string var calc; // used for calculation of each digit // Determine if the ccNumb is in fact all numbers for (var j=0; j<len; j++) { temp = '' + sCCN.substring(j, j+1); if (valid.indexOf(temp) == '-1') bNum = false; } if(!bNum) return false; // if it is NOT a number, you can either alert to the fact, or just pass a failure if(len==0) return false; // Determine if it is the proper length if(len>19) return false; //Apparently Diner Club can have 19 digits *NEW* if(len<12) return false; //Apparently Maestro can have 12 digits *NEW* // Let see if it is a valid card number for(var i=len;i>0;i--) // LOOP throught the digits of the card { calc = parseInt(iCCN) % 10; // right most digit calc = parseInt(calc); // assure it is an integer iTotal += calc; // running total of the card number as we loop - Do Nothing to first digit i--; // decrement the count - move to the next digit in the card iCCN = iCCN / 10; // subtracts right most digit from ccNumb calc = parseInt(iCCN) % 10 ; // NEXT right most digit calc = calc *2; // multiply the digit by two // Instead of some screwy method of converting 16 to a string and then parsing 1 and 6 and then adding them to make 7, // I use a simple switch statement to change the value of calc2 to 7 if 16 is the multiple. switch(calc) { case 10: calc = 1; break; //5*2=10 & 1+0 = 1 case 12: calc = 3; break; //6*2=12 & 1+2 = 3 case 14: calc = 5; break; //7*2=14 & 1+4 = 5 case 16: calc = 7; break; //8*2=16 & 1+6 = 7 case 18: calc = 9; break; //9*2=18 & 1+8 = 9 default: calc = calc; //4*2= 8 & 8 = 8 -same for all lower numbers } iCCN = iCCN / 10; // subtracts right most digit from ccNum iTotal += calc; // running total of the card number as we loop } // END OF LOOP if ((iTotal%10)==0) return true; // check to see if the sum Mod 10 is zero return false; } 
-one
source

All Articles