Skip to content

Commit c3ed0d1

Browse files
committed
Implement credit card validator function
1 parent 28dfefd commit c3ed0d1

File tree

1 file changed

+45
-3
lines changed

1 file changed

+45
-3
lines changed
Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,48 @@
1-
function passwordValidator(password) {
2-
return password.length < 5 ? false : true
1+
function isValidCreditCard(cardNumber) {
2+
// Check if cardNumber is exactly 16 characters and all are digits
3+
if (!/^\d{16}$/.test(cardNumber)) {
4+
return false;
5+
}
6+
7+
// Check if card has at least two different digits
8+
if (/^(\d)\1{15}$/.test(cardNumber)) {
9+
return false;
10+
}
11+
12+
// Check if last digit is even
13+
const lastDigit = Number(cardNumber[15]);
14+
if (lastDigit % 2 !== 0) {
15+
return false;
16+
}
17+
18+
// Calculate the sum of all digits and check if greater than 16
19+
const sum = cardNumber.split('').reduce((acc, digit) => acc + Number(digit), 0);
20+
if (sum <= 16) {
21+
return false;
22+
}
23+
24+
// All conditions passed, card is valid
25+
return true;
326
}
427

28+
// Example usage:
29+
// console.log(isValidCreditCard("9999777788880000")); // true
30+
// console.log(isValidCreditCard("4444444444444444")); // false
31+
32+
module.exports = isValidCreditCard;
33+
34+
/*
35+
36+
Explanation:
37+
38+
The first if uses a regular expression to ensure the card number is exactly 16 digits long and contains only digits.
39+
40+
The second if uses a regex to check if all digits are the same (e.g., all '4's).
41+
42+
Then, we check if the last digit is even using modulo %.
43+
44+
Then, we calculate the sum of all digits with reduce and ensure it is greater than 16.
45+
46+
Finally, we return true if all these checks pass, else false.
547
6-
module.exports = passwordValidator;
48+
*/

0 commit comments

Comments
 (0)