// The function determines
whether a Credit Card number is "valid"
// Please note that a "valid" Credit Card number is not
essentially a Credit Card in "Good Standing"
// When users type their Credit Card
number
// they usually use hyphens to separate the numbers into blocks
function isValidCreditCard(number)
{
if (number.indexOf("-"))
{ // checking to see if there is a hyphen
// split out the numbers from the string which is delimited by
the (-)
// &
put the individual number blocks into individual array elements
// ie,
number = "12-34", cc = number.split("-")
=> cc[0] == 12 & cc[1] == 34
cc = number.split("-");
number =
""; // "empty" the
variable so that we can "reuse" it
for (var i = 0; i
< cc.length; i++) {
number += cc[i]; // here we are rebuilding
the string (number) without the delimiter (-)
}
}
// instead of
splitting on the (-) this time split on a space
if (number.indexOf("
")) {
cc = number.split("
");
number = cc.join("");
}
//
OR using RegExp we can combine the above two
//
replace either a "-" or a " " with an empty string
globally
//
number = number.replace(/-|\s/g,
"");
/***** The rest of the algorithm is
beyond the scope of this course *****/
if (number.length > 19) return (false);
sum = 0; mul = 1; l = number.length;
for (i = 0; i < l; i++) {
digit =
number.substring(l - i - 1, l - i);
tproduct =
parseInt(digit, 10) * mul;
if (tproduct
>= 10) sum += (tproduct % 10) + 1;
else sum +=
tproduct;
if (mul == 1) mul++;
else mul--;
}
if ((sum % 10) == 0) return (true);
else return (false);
} |