Skip to content

Commit 7d41a42

Browse files
committed
Create card validator with all 4 rules and tests for valid and invalid card numbers
1 parent b04e9e7 commit 7d41a42

2 files changed

Lines changed: 61 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Validates a credit card number string against the following rules:
2+
// - Must be exactly 16 digits (no letters or other characters)
3+
// - Must contain at least two different digits
4+
// - The final digit must be even
5+
// - The sum of all digits must be greater than 16
6+
7+
function isValidCardNumber(cardNumber) {
8+
// Rule 1: must be exactly 16 digit characters
9+
if (!/^\d{16}$/.test(cardNumber)) return false;
10+
11+
const digits = cardNumber.split("").map(Number);
12+
13+
// Rule 2: at least two different digits must be present
14+
if (new Set(digits).size < 2) return false;
15+
16+
// Rule 3: final digit must be even
17+
if (digits[15] % 2 !== 0) return false;
18+
19+
// Rule 4: sum of all digits must be greater than 16
20+
const sum = digits.reduce((acc, d) => acc + d, 0);
21+
if (sum <= 16) return false;
22+
23+
return true;
24+
}
25+
26+
module.exports = isValidCardNumber;
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
const isValidCardNumber = require("./card-validator");
2+
3+
// Valid cards
4+
test("should return true for a valid card number", () => {
5+
expect(isValidCardNumber("9999777788880000")).toEqual(true);
6+
expect(isValidCardNumber("6666666666661666")).toEqual(true);
7+
});
8+
9+
// Rule 1: must be exactly 16 digits
10+
test("should return false when card contains non-digit characters", () => {
11+
expect(isValidCardNumber("a92332119c011112")).toEqual(false);
12+
});
13+
14+
test("should return false when card has fewer than 16 digits", () => {
15+
expect(isValidCardNumber("123456789012345")).toEqual(false);
16+
});
17+
18+
test("should return false when card has more than 16 digits", () => {
19+
expect(isValidCardNumber("12345678901234567")).toEqual(false);
20+
});
21+
22+
// Rule 2: at least two different digits
23+
test("should return false when all digits are the same", () => {
24+
expect(isValidCardNumber("4444444444444444")).toEqual(false);
25+
});
26+
27+
// Rule 3: final digit must be even
28+
test("should return false when final digit is odd", () => {
29+
expect(isValidCardNumber("6666666666666661")).toEqual(false);
30+
});
31+
32+
// Rule 4: sum of all digits must be greater than 16
33+
test("should return false when sum of digits is not greater than 16", () => {
34+
expect(isValidCardNumber("1111111111111110")).toEqual(false);
35+
});

0 commit comments

Comments
 (0)