This repository has been archived by the owner on Sep 13, 2022. It is now read-only.
forked from stevenmills/bootstrapvalidator
-
Notifications
You must be signed in to change notification settings - Fork 3
/
creditCard.js
45 lines (39 loc) · 1.4 KB
/
creditCard.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
(function($) {
$.fn.bootstrapValidator.validators.creditCard = {
/**
* Return true if the input value is valid credit card number
* Based on https://gist.github.com/DiegoSalazar/4075533
*
* @param {BootstrapValidator} validator The validator plugin instance
* @param {jQuery} $field Field element
* @param {Object} options Can consist of the following key:
* - message: The invalid message
* @returns {Boolean}
*/
validate: function(validator, $field, options) {
var value = $field.val();
if (value == '') {
return true;
}
// Accept only digits, dashes or spaces
if (/[^0-9-\s]+/.test(value)) {
return false;
}
// The Luhn Algorithm
// http://en.wikipedia.org/wiki/Luhn
value = value.replace(/\D/g, '');
var check = 0, digit = 0, even = false, length = value.length;
for (var n = length - 1; n >= 0; n--) {
digit = parseInt(value.charAt(n), 10);
if (even) {
if ((digit *= 2) > 9) {
digit -= 9;
}
}
check += digit;
even = !even;
}
return (check % 10) == 0;
}
};
}(window.jQuery));