Code2night
  • Home
  • Blogs
  • Tutorial
  • Post Blog
  • Tools
    • Json Beautifier
    • Html Beautifier
  • Members
    • Register
    • Login
  1. Home
  2. Blogpost
21 Oct
2021

Card Number Formatting using jquery

by Shubham Batra

1306

Card Types - 

So to start from , there are different types of card available around the world and some use there own format which can be different than others. Some of those Cards are these

Amex(American Express) - 371449635398431

MasterCard - 5200828282828210

VISA - 4000056655665556

So, you can see some difference in the formatting across cards and so it becomes tough  to implement correct formatting while the user types the card number. So for implementing that we will take one input box and add some script on page





 <div class="col-md-6" style="padding:50px;">

    <input type="text" id="txtcard" onkeypress="return formatCardNumber(event)" />

</div>
 <script>
 
 var defaultFormat = /(?:^|\s)(\d{4})$/;

   var cards = [
        {
            type: 'maestro',
            patterns: [5018, 502, 503, 506, 56, 58, 639, 6220, 67],
            format: defaultFormat,
            length: [12, 13, 14, 15, 16, 17, 18, 19],
            cvcLength: [3],
            luhn: true
        }, {
            type: 'forbrugsforeningen',
            patterns: [600],
            format: defaultFormat,
            length: [16],
            cvcLength: [3],
            luhn: true
        }, {
            type: 'dankort',
            patterns: [5019],
            format: defaultFormat,
            length: [16],
            cvcLength: [3],
            luhn: true
        }, {
            type: 'visa',
            patterns: [4],
            format: defaultFormat,
            length: [13, 16],
            cvcLength: [3],
            luhn: true
        }, {
            type: 'mastercard',
            patterns: [51, 52, 53, 54, 55, 22, 23, 24, 25, 26, 27],
            format: defaultFormat,
            length: [16],
            cvcLength: [3],
            luhn: true
        }, {
            type: 'amex',
            patterns: [34, 37],
            format: /(\d{1,4})(\d{1,6})?(\d{1,5})?/,
            length: [15],
            cvcLength: [3, 4],
            luhn: true
        }, {
            type: 'dinersclub',
            patterns: [30, 36, 38, 39],
           format: /^(\d{4}|\d{4}\s\d{6})$/,
            length: [14],
            cvcLength: [3],
            luhn: true
        }, {
            type: 'discover',
            patterns: [60, 64, 65, 622],
            format: defaultFormat,
            length: [16],
            cvcLength: [3],
            luhn: true
        }, {
            type: 'unionpay',
            patterns: [62, 88],
            format: defaultFormat,
            length: [16, 17, 18, 19],
            cvcLength: [3],
            luhn: false
        }, {
            type: 'jcb',
            patterns: [35],
            format: defaultFormat,
            length: [16],
            cvcLength: [3],
            luhn: true
        }
    ];
  var formatCardNumber = function (e) {
        var $target, card, digit, length, re, upperLength, value;
        digit = String.fromCharCode(e.which);
        if (!/^\d+$/.test(digit)) {
            return;
        }
        $target = $(e.currentTarget);
      value = $target.val();
      debugger;
        card = cardFromNumber(value + digit);
      length = (value.replace(/\D/g, '') + digit).length;
      if (length > Math.max.apply(null, card.length)) {
          return false;
      }
        upperLength = 16;
        if (card) {
            upperLength = card.length[card.length.length - 1];
        }
        if (length >= upperLength) {
            return;
        }
        if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== value.length) {
            return;
        }
        if (card && card.type === 'amex') {
            re = /^(\d{4}|\d{4}\s\d{6})$/;
        } else {
            if (card != null && card != undefined) {
                re = card.format// /(?:^|\s)(\d{4})$/;
            }
            else {
                re =  /(?:^|\s)(\d{4})$/;
            }
        }
        if (re.test(value)) {
            e.preventDefault();
            return setTimeout(function () {
                return $target.val(value + ' ' + digit);
            });
        } else if (re.test(value + digit)) {
            e.preventDefault();
            return setTimeout(function () {
                return $target.val(value + digit + ' ');
            });
        }
    };
   var cardFromNumber = function (num) {
        var card, p, pattern, _i, _j, _len, _len1, _ref;
        num = (num + '').replace(/\D/g, '');
        for (_i = 0, _len = cards.length; _i < _len; _i++) {
            card = cards[_i];
            _ref = card.patterns;
            for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
                pattern = _ref[_j];
                p = pattern + '';
                if (num.substr(0, p.length) === p) {
                    return card;
                }
            }
        }
    };
	</script>

So, this code is using jquery so make sure you have added the jquery reference on the page before using this. So, about this script in this we have added some predefined card formats in the array along with there max character size. And we are calling formatCardNumber   on keypress of input box. Which find the card type based on starting characters and format accordingly. You can see the output with different card number and output format

With MasterCard

With Visa card Format

With Amex Card Format

So, you can see the formatting working differently with different card types. So this is how we can implement Card Number formatting with Jquery. If you have any issues you can comment and ask.

  • |
  • Card Number Formatting , Amex Card Format , Card Format

Comments

Tags

How to set Date and time format in IIS Manager
IIS Manager
IIS
Internet Information Services (IIS) Manager
Internet Information Services (IIS)
Internet Information Services
Error Handling In AspNet Core
Exception Handling Asp Net Core
Exception Handling
Exception Handling Asp Net
Aspnet
Creating Log Files in MVC
Error Handling in MVC
Exception Handling in AspNet
Handling Exceptions and Creating Error Logs in Asp net Mvc using base controller
net
Code2Tonight
Stopping Browser Reload On Save
Repository Pattern with ADONet in MVC
Repository Pattern With ASPNET MVC And AdoNet
MVC Crud Operation
Jquery Full Calender Integrated With ASPNET
Full Calendar
Jquery Calendar
Slick Slider
Slick Slider Example
responsive carousels
Entity Framework
MVC
Intergrate SummerNote Text Editor into AspNet MVC
Web Config
Auto Redirection
Redirection from Http to https
AspNet
Url Rewriting
Implement Stripe Payment Gateway In ASPNET Core
Stripe Payment Gateway
C#
AspNet Core
StripeNet
Postgre
PgAdmin4
PostgreSql
A Non Fatal Error Occured During Cluster Initialisation In Postgre SQL
Microsoft Outlook
Outlook Appointments
Microsoft Exchange Service
Send Email With HTML Template And PDF Using ASPNet C#
Send Email
Email with html template
email with pdf attachment
email with html and pdf
Microsoft Outlook Contacts
Outlook
Microsoft Exhchange Service
JSON
Convert string with dot notation to JSON
HTTP Error 5025 ANCM Out Of Process Startup Failure
Internet Information Service
Net core
Payumoney Integration With AspNet MVC
Prism js
Highlighting Syntax
Syntax Highlighting
code stylings
c#
Jquery AJax
Ajax
Jquery
Implement Stripe Payment Gateway In ASPNET
Using Checkout in an ASPNET Web Forms application
Stripe Payment
Stripe Payment Integration
Stripe Integeration
How to upload Image file using AJAX andjQuery
upload Image file using AJAX and jquery
Ajax call
file upload using ajax
file uploading using ajax and jquery
ConfigurationBuilder does not contain a definition for SetBasePath
Reading app json file in dot net core
Appsetting jso
Dot Net Core
Globalization and localization in ASPNET Core
Asp Net Core with Resource file resx
How to get the resx file strings in asp net core
Culture in Net core
Localisation in AspNet Core
Url Encryption in AspNet MVC
Url Encryption in C#
Url Encryption
Custom Helpers
Slick Slider with single slide
Slick
Vue js
Child Components
How to reload vue js child components
Net Core
Visual Studio
Net core 31
Razor
Zoom sdk
Zoom c# wrapper Inegration
zoom Integration in c#
Zoom Integration
Zoom window sdk
vue js toggle button
vue js
toggle buttons
vuejs
vue js toggle switch
SignalR
VueJs
SignalR in Net Core
Chat App in Vue js
Chat App using SignalR
AspNet Chat app
JPlayer
Html5 Audio Video Player
Music Player
QR Code Generator
QR Code
Jquery QR Code
AspNet MVC
Google Maps
Google map api
Places API
Google map Places API in AspNet
Jquery Autocomplete
Autocomplete
Jquery UI Autocomplete
ExcelDataReader
Import data from excel in AspNet
Card Number Formatting
Amex Card Format
Card Format
FCM
Cloud Messaging
Android Notifications
FCM Notifications for IOS
IOS Notifications
Angular js
apply css on child components in Angular js
Angular Mentions
Google Sign In
Google Login
Google Oauth Api
Social Login
Aspnet Mvc
Google + Api
Create and publish a package using Visual Studio (NET Framework
Windows)
Create and publish a nuget package
create your own nuget package
Image compress
Image optimization
compress Image
optimize Image
WebForm
AspNet Web Pages
Batch Script
Database backup
Powershell
ASpNet
Sql Server Backup
AspNet core 31
Aspnet core 21
HttpCookies in AspNet Core
LinkedIn Authentication
Login using LinkedIN
Social Login in AspNet
LinkedIn Authentication in AspNet MVC
LinkedIn Login in aspnet MVC
Shuffle List in c#
C#Net
Google Login in AspNet MVC
GoogleAuthentication Nuget package
Password Encryption
RFC Encryption
Encryption and Decryption
Encryption in AspNet
Base 64 Encryption
Base 64 Decryption
Swagger UI
Swashbuckle
SwashbuckleAspNetCore
Rest API
Postman
Api Testing
SSRS
SSRS Report
ASPNET MVC
ASPNET MVC SSRS Report
ssrs report
XlWorkbook
ClosedXml
Excel Export
Blazor
Syncfusion
SFGrid
Syncfusion SFgrid
Net
Net core 60
DataTable to List
Extension Methods
Microsoft Access Database Engine
Ace Ole Db 120
MicrosoftACEOLEDB120
OLE DB
Aspnet MVC
Ace OLE DB

Welcome To Code2night, A common place for sharing your programming knowledge,Blogs and Videos

  • Kurukshetra
  • [email protected]

Links

  • Home
  • Blogs
  • Tutorial
  • Post Blog

Popular Tags

Copyright © 2022 by Code2night. All Rights Reserved

  • Home
  • Blog
  • Login
  • SignUp
  • Contact
  • Json Beautifier