Credit Card Number Format

How to format and verify a credit card number with spaces between four digits as you type:

eg: 4464 6846 4354 3564 

I tried:

 $('.creditno').keyup(function() { cc = $(this).val().split("-").join(""); cc = cc.match(new RegExp('.{1,4}$|.{1,4}', 'g')).join("-"); $(this).val(cc); }); 

Please, help

+7
source share
8 answers

Try the following:

 function cc_format(value) { var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '') var matches = v.match(/\d{4,16}/g); var match = matches && matches[0] || '' var parts = [] for (i=0, len=match.length; i<len; i+=4) { parts.push(match.substring(i, i+4)) } if (parts.length) { return parts.join(' ') } else { return value } } 

Note. For more information see https://www.peterbe.com/plog/cc-formatter .

To prevent a user from entering only a number:

Javascript way

 <input type="text" id="txt_cardNumber" name="txt_cardNumber" onkeypress="return checkDigit(event)"> function checkDigit(event) { var code = (event.which) ? event.which : event.keyCode; if ((code < 48 || code > 57) && (code > 31)) { return false; } return true; } 

OR

 function checkDigit() { var allowedChars = "0123456789"; var entryVal = document.getElementById('txt_cardNumber').value(); var flag; for(var i=0; i<entryVal.length; i++){ flag = false; for(var j=0; j<allowedChars.length; j++){ if(entryVal.charAt(i) == allowedChars.charAt(j)) { flag = true; } } if(flag == false) { entryVal = entryVal.replace(entryVal.charAt(i),""); i--; } } return true; } 

HTML5 path

 <input type="text" id="txt_cardNumber" name="txt_cardNumber" pattern="[0-9.]+"> <input type="number" id="txt_cardNumber" name="txt_cardNumber"> 

jQuery Way

 $("#txt_cardNumber").keypress(function (e) { if ((e.which < 48 || e.which > 57) && (e.which !== 8) && (e.which !== 0)) { return false; } return true; }); 

Note. Please check here for more information on the various key code.

+12
source

I could not find a reasonable solution that works with text editing, so here you go:

 $("#cardNumber").on("keydown", function(e) { var cursor = this.selectionStart; if (this.selectionEnd != cursor) return; if (e.which == 46) { if (this.value[cursor] == " ") this.selectionStart++; } else if (e.which == 8) { if (cursor && this.value[cursor - 1] == " ") this.selectionEnd--; } }).on("input", function() { var value = this.value; var cursor = this.selectionStart; var matches = value.substring(0, cursor).match(/[^0-9]/g); if (matches) cursor -= matches.length; value = value.replace(/[^0-9]/g, "").substring(0, 16); var formatted = ""; for (var i=0, n=value.length; i<n; i++) { if (i && i % 4 == 0) { if (formatted.length <= cursor) cursor++; formatted += " "; } formatted += value[i]; } if (formatted == this.value) return; this.value = formatted; this.selectionEnd = cursor; }); 

A keydown listener keydown needed to adjust the cursor position for backspace and delete to move spaces. It cannot be used to restrict character input, since you do not want to use key codes for this.

The input listener rebuilds the text, breaks non-numbers, adds spaces every 4 characters, and keeps the cursor position.

+4
source

To find

Plunker for formatting credit card numbers

using the angularjs directive. Format card numbers in xxxxxxxxxxxx3456 Fromat.

 angular.module('myApp', []) .directive('maskInput', function() { return { require: "ngModel", restrict: "AE", scope: { ngModel: '=', }, link: function(scope, elem, attrs) { var orig = scope.ngModel; var edited = orig; scope.ngModel = edited.slice(4).replace(/\d/g, 'x') + edited.slice(-4); elem.bind("blur", function() { var temp; orig = elem.val(); temp = elem.val(); elem.val(temp.slice(4).replace(/\d/g, 'x') + temp.slice(-4)); }); elem.bind("focus", function() { elem.val(orig); }); } }; }) .controller('myCtrl', ['$scope', '$interval', function($scope, $interval) { $scope.creditCardNumber = "1234567890123456"; }]); 
+2
source

I just wrote this to handle Visa, Discover, Master Card, and Amex (with formatting and card type identification).

 // SAMPLE FIELD: <input type="text" name="cstCCNumber" id="cstCCNumber" value=""onkeyup="cc_format('cstCCNumber','cstCCardType');"> function cc_format(ccid,ctid) { // supports Amex, Master Card, Visa, and Discover // parameter 1 ccid= id of credit card number field // parameter 2 ctid= id of credit card type field var ccNumString=document.getElementById(ccid).value; ccNumString=ccNumString.replace(/[^0-9]/g, ''); // mc, starts with - 51 to 55 // v, starts with - 4 // dsc, starts with 6011, 622126-622925, 644-649, 65 // amex, starts with 34 or 37 var typeCheck = ccNumString.substring(0, 2); var cType=''; var block1=''; var block2=''; var block3=''; var block4=''; var formatted=''; if (typeCheck.length==2) { typeCheck=parseInt(typeCheck); if (typeCheck >= 40 && typeCheck <= 49) { cType='Visa'; } else if (typeCheck >= 51 && typeCheck <= 55) { cType='Master Card'; } else if ((typeCheck >= 60 && typeCheck <= 62) || (typeCheck == 64) || (typeCheck == 65)) { cType='Discover'; } else if (typeCheck==34 || typeCheck==37) { cType='American Express'; } else { cType='Invalid'; } } // all support card types have a 4 digit firt block block1 = ccNumString.substring(0, 4); if (block1.length==4) { block1=block1 + ' '; } if (cType == 'Visa' || cType == 'Master Card' || cType == 'Discover') { // for 4X4 cards block2 = ccNumString.substring(4, 8); if (block2.length==4) { block2=block2 + ' '; } block3 = ccNumString.substring(8, 12); if (block3.length==4) { block3=block3 + ' '; } block4 = ccNumString.substring(12, 16); } else if (cType == 'American Express') { // for Amex cards block2 = ccNumString.substring(4, 10); if (block2.length==6) { block2=block2 + ' '; } block3 = ccNumString.substring(10, 15); block4=''; } else if (cType == 'Invalid') { // for Amex cards block1 = typeCheck; block2=''; block3=''; block4=''; alert('Invalid Card Number'); } formatted=block1 + block2 + block3 + block4; document.getElementById(ccid).value=formatted; document.getElementById(ctid).value=cType; } 
+2
source
 <?php function luhn_check($number) { // Strip any non-digits (useful for credit card numbers with spaces and hyphens) $number=preg_replace('/\D/', '', $number); // Set the string length and parity $number_length=strlen($number); $parity=$number_length % 2; // Loop through each digit and do the maths $total=0; for ($i=0; $i<$number_length; $i++) { $digit=$number[$i]; // Multiply alternate digits by two if ($i % 2 == $parity) { $digit*=2; // If the sum is two digits, add them together (in effect) if ($digit > 9) { $digit-=9; } } // Total up the digits $total+=$digit; } // If the total mod 10 equals 0, the number is valid return ($total % 10 == 0) ? TRUE : FALSE; } ?> 
+1
source
 function testCreditCard () { myCardNo = document.getElementById('CardNumber').value; myCardType = document.getElementById('CardType').value; if (checkCreditCard (myCardNo,myCardType)) { alert ("Credit card has a valid format") } else {alert (ccErrors[ccErrorNo])}; } 

check this link for lib http://www.braemoor.co.uk/software/creditcard.shtml

+1
source

 function cc_format(value) { var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '') var matches = v.match(/\d{4,16}/g); var match = matches && matches[0] || '' var parts = [] for (i=0, len=match.length; i<len; i+=4) { parts.push(match.substring(i, i+4)) } if (parts.length) { return parts.join(' ') } else { return value } } onload = function() { document.getElementById('cc').oninput = function() { this.value = cc_format(this.value) } } function checkDigit(event) { var code = (event.which) ? event.which : event.keyCode; if ((code < 48 || code > 57) && (code > 31)) { return false; } return true; } 
 <form> <input id="cc" value="" placeholder="1234 1234 1234 1234" onkeypress="return checkDigit(event)"> </form> 

Demo version of the check digit and formatting the CC card number

+1
source

using vanilla js

JavaScript:

 function formatCreditCardOnKey(event) { //on keyup, check for backspace to skip processing var code = (event.which) ? event.which : event.keyCode; if(code != 8) formatCreditCard(); else{ //trim whitespace from end; trimEnd() doesn't work in IE document.getElementById("cardNumber").value = document.getElementById("cardNumber").value.replace(/\s+$/, ''); } } function formatCreditCard() { var cardField = document.getElementById("cardNumber"); //remove all non-numeric characters var realNumber = cardField.value.replace(/\D/g,''); var newNumber = ""; for(var x = 1; x <= realNumber.length; x++){ //make sure input is a digit if (isNumeric(realNumber.charAt(x-1))) newNumber += realNumber.charAt(x-1); //add space every 4 numeric digits if(x % 4 == 0 && x > 0 && x < 15) newNumber += " "; } cardField.value = newNumber; } function isNumeric(char){ return('0123456789'.indexOf(char) !== -1); } 

HTML:

 <input type="text" id="cardNumber" maxlength="19" onKeyUp="formatCreditCardOnKey(event)" onBlur="formatCreditCard()" onFocus="formatCreditCard()"/> 

This works (for me) with autocompletion, allows the user to use the Backspace key, as expected (they do not need to remove spaces), and does not allow (other) non-numeric characters.

0
source

Source: https://habr.com/ru/post/1247844/


All Articles