How to detect and validate credit card numbers in jQuery
We have received many requests from our readers about credit card validation on client side so today in this tutorial I am going to show you that how to detect and validate a credit card using a jQuery library. It will show you type of detected credit card and calculate the length of the credit card number by its type.
We used jQuery Credit Card Validator library to perform this validation.
jQuery
Include Library:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="jquery.creditCardValidator.js"></script>
Create text box to get credit card number.
<form> <h4>Credit Card Number</h4> <ul> <li><input type="text" name="card_number" id="card_number" placeholder="1234 5678 9012 3456"></li> </ul> </form>
Initialize validation library for id=”card_number”.
<script> $(function() { $('#card_number').validateCreditCard(function(result) { if(result.card_type == null) { $('#card_number').removeClass(); } else { $('#card_number').addClass(result.card_type.name); } if(!result.valid) { $('#card_number').removeClass("valid"); } else { $('#card_number').addClass("valid"); } }); }); </script>
Above jQuery simply add and remove class from text field to show credit card image and valid tick mark few more js codes to show Length validation and Lunh validation:
$('.log').html(Length valid: ' + result.length_valid + ' Luhn valid: ' + result.luhn_valid);
You can use this library to make client side validation to show beautiful form to your clients. Demo and free code download aided first check demo if you like it then download it.
I hope you like this simple and easy tutorial please feel free to comment below.
Tutorial Categories:
Thanks for a good tutorial.. 🙂