creditCard.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. (function($) {
  2. $.fn.bootstrapValidator.validators.creditCard = {
  3. /**
  4. * Return true if the input value is valid credit card number
  5. * Based on https://gist.github.com/DiegoSalazar/4075533
  6. *
  7. * @param {BootstrapValidator} validator The validator plugin instance
  8. * @param {jQuery} $field Field element
  9. * @param {Object} options Can consist of the following key:
  10. * - message: The invalid message
  11. * @returns {boolean}
  12. */
  13. validate: function(validator, $field, options) {
  14. var value = $field.val();
  15. // Accept only digits, dashes or spaces
  16. if (/[^0-9-\s]+/.test(value)) {
  17. return false;
  18. }
  19. // The Luhn Algorithm
  20. // http://en.wikipedia.org/wiki/Luhn
  21. value = value.replace(/\D/g, '');
  22. var check = 0, digit = 0, even = false, length = value.length;
  23. for (var n = length - 1; n >= 0; n--) {
  24. digit = parseInt(value.charAt(n), 10);
  25. if (even) {
  26. if ((digit *= 2) > 9) {
  27. digit -= 9;
  28. }
  29. }
  30. check += digit;
  31. even = !even;
  32. }
  33. return (check % 10) == 0;
  34. }
  35. };
  36. }(window.jQuery));