This code snippet provides a simple and effective way to validate credit card numbers in Angular. It utilizes an Angular directive called “cardValidation” to handle the validation process. By implementing this directive, you can easily validate credit card numbers and determine their card type, including Mastercard, Visa, Amex, and Discover. With clear instructions and helpful comments, this code snippet allows you to integrate credit card validation seamlessly into your Angular project.
The code snippet also incorporates the widely-used Luhn algorithm to perform the actual validation. By following the algorithm’s steps, the code accurately determines whether a credit card number is valid or not. Additionally, it applies the appropriate card type based on the card number pattern, ensuring accurate identification.
How to Validate Credit Card in AngularJS
First of all, create the HTML structure for the credit card validation feature:
<div ng-app="storeApp" ng-controller="MainCtrl" ng-form="cardValidation" ng-class="validity ? 'valid' : 'invalid'"> <div> <p><b>Select Card type and enter card no:</b></p> <card-validation name="cardNo" ng-model="card.number"></card-validation> <span class='msg' ng-class="validity ? 'valid' : 'invalid'">{{msg}}<span></div> <hr> <h2>Valid credit card numbers to test : </h2> <div><b>Visa :</b> 4532069777249404 , 4916014173889326 </div> <div><b>Master :</b> 5194775997768660, 5494872713298895</div> <div><b>Amex :</b> 340251740623507, 375921122764396</div> <div><b>Discover :</b> 6011489471829878 , 6011782582773435</div> <h2>This directive has been build based on Luhn algorithm:<h2> <pre>Ref : <a href='https://en.wikipedia.org/wiki/Luhn_algorithm'>https://en.wikipedia.org/wiki/Luhn_algorithm</a> </pre> <h3>Prefix, Length, and Check Digit Criteria</h3> <table border="1"> <tbody><tr><td ><b>CARD TYPE</b> </td><td ><b>Prefix</b> </td><td><b>Length</b> </td><td><b>Check digit algorithm</b> </td></tr> <tr><td width="148">MASTERCARD</td><td width="86">51-55</td><td width="78">16 </td><td width="120">mod 10</td></tr> <tr><td width="148">VISA</td><td width="86">4</td><td width="78">13, 16 </td><td width="120">mod 10</td></tr> <tr><td width="148">AMEX</td><td width="86">34 <br> 37</td><td width="78">15 </td><td width="120">mod 10</td></tr> <tr><td width="148">Diners Club/<br> Carte Blanche</td><td width="86">300-305<br> 36<br> 38 </td><td width="78">14</td><td width="120">mod 10</td></tr> <tr><td width="148">Discover</td><td width="86">6011</td><td width="78">16 </td><td width="120">mod 10</td></tr> <tr><td width="148">enRoute</td><td width="86">2014<br> 2149</td> <td width="78">15</td><td width="120">any</td></tr> <tr><td width="148">JCB</td><td width="86">3</td><td width="78">16</td> <td width="120">mod 10</td></tr> <tr><td width="148">JCB</td><td width="86">2131<br> 1800</td><td width="78">15 </td><td width="120">mod 10</td></tr> </tbody></table> <h3>LUHN Formula (Mod 10) for Validation of Primary Account Number </h3> <p>Step 1: Double the value of alternate digits of the primary account number beginning with the second digit from the right (the first right--hand digit is the check digit.)</p> <p>Step 2: Add the individual digits comprising the products obtained in Step 1 to each of the unaffected digits in the original number.</p> <p>Step 3: The total obtained in Step 2 must be a number ending in zero (30, 40, 50, etc.) for the account number to be validated.</p> <p></p> </div>
Add the following CSS styles for the basic card validation interface.
body { font-family: verdana; font-size:12px; } input, select { height:30px; margin:10px 10px 10px 0; border:2px solid #aaa; padding: 0 5px; } input.ng-pristine.ng-valid.ng-empty { background-color: #FFF; } input.ng-invalid.ng-dirty , div.invalid input { background-color: #FA787E; } .valid input.ng-valid.ng-dirty { background-color: #78FA89; } .msg { font-weight:700; } .msg.valid { color : #008000; } .msg.invalid { color : #FF0000; } label { margin-right:45px; }
Now, load the AngularJS by adding the following CDN link before closing the body tag:
<script src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js'></script>
Finally, use the following JavaScript function for card validation feature. Within the code, you’ll notice a function called cardValidation()
, which performs the actual validation using the renowned Luhn algorithm. You can customize this function or enhance it with additional validation checks based on your specific requirements. For instance, you might want to include checks for expiration date or CVV verification.
console.clear(); var app = angular.module('storeApp', []); app.controller('MainCtrl', function($scope) { $scope.msg = ''; $scope.validity = false; }); app.directive("cardValidation", function() { return { require: "?ngModel", template: "<label>Card Type</label><label>Card No</label><br><select ng-change='onChange()' required ng-model='type'><option value='Mastercard'>Mastercard</option><option value='Visa'>Visa</option><option value='Amex'>Amex</option><option value='Discover'>Discover</option></select>" + "<input ng-model='value' ng-change='onChange()' minlength='13' maxlength='19' data-ng-pattern='/^[0-9]+$/' placeholder='Enter credit card no here...'>", link: function(scope, element, attrs, ngModel) { if (!ngModel) return; scope.onChange = function() { ngModel.$setViewValue(scope.value); ngModel.$setViewValue(scope.type); if (scope.value && scope.type) { cardValidation(scope.value, scope.type); } }; ngModel.$render = function() { scope.type = ngModel.$modelValue; scope.value = ngModel.$modelValue; scope.type = 'Visa'; }; //card number validation function function cardValidation(cardNumber, type) { var backwards = 0; var multiplyx2 = ""; var total = 0; /* For-loop going through the number. It begins at the second digit from the end. Then it adds to "backwards" every other digit going backwards through the number. */ for (i = cardNumber.length - 2; i >= 0; i -= 2) { backwards += cardNumber.charAt(i); } /* For-loop going through the digits in "backwards" and multiplying them by 2. The multiplied digits are stored in "multiplyx2".*/ for (i = 0; i < backwards.length; i++) { multiplyx2 += backwards.charAt(i) * 2; } /* The digits in "multiplyx2" are added up and stored in "total". */ for (i = 0; i < multiplyx2.length; i++) { total += parseInt(multiplyx2.charAt(i)); } /* Adding up the digits that have been left out. Starting with the third digit from the end. These digits are added to "total". */ for (i = cardNumber.length - 3; i >= 0; i -= 2) { total += parseInt(cardNumber.charAt(i)); } /* Adding the last digit in the card number to "total". Could have done so in previous loop but just for the sake of it (that's how the Luhn algorithm goes) . */ total += parseInt(cardNumber.charAt(cardNumber.length - 1)) /* Testing if "total" can be divided by 10 without leaving a remainder. */ if ((total % 10) == 0 && type === cardType(cardNumber)) { scope.validity = true; scope.msg = type + ' Card is valid'; } else { scope.validity = false; scope.msg = type + ' Card is not valid'; } }; // function for crad type function cardType(cardNumber) { var cardType = (/^5[1-5]/.test(cardNumber)) ? "Mastercard" : (/^4/.test(cardNumber)) ? "Visa" : (/^3[47]/.test(cardNumber)) ? 'Amex' : (/^6011|65|64[4-9]|622(1(2[6-9]|[3-9]\d)|[2-8]\d{2}|9([01]\d|2[0-5]))/.test(cardNumber)) ? 'Discover' : Unknown return cardType; } } }; });
That’s all! hopefully, you have successfully integrated this Angular credit card validation feature into your project. If you have any questions or suggestions, feel free to comment below.