Skip to content

Commit 4dba153

Browse files
author
Ogbemi mene
committed
md. validation
1 parent 8803f92 commit 4dba153

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

Sprint-3/4-stretch/card-validator.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,39 @@ These are the requirements your project needs to fulfill:
3333
- Return a boolean from the function to indicate whether the credit card number is valid.
3434

3535
Good luck!
36+
37+
38+
function validateCreditCard(cardNumber) {
39+
// Requirement Rule 1: Must be exactly 16 characters long and contain only numbers
40+
const is16Digits = /^\d{16}$/.test(cardNumber);
41+
if (!is16Digits) {
42+
return false;
43+
}
44+
45+
// Convert the string into an array of integers for numerical calculations
46+
const digits = cardNumber.split("").map(Number);
47+
48+
// Requirement Rule 2: Must have at least two different digits represented
49+
// We use a Set because it automatically filters out duplicate values
50+
const uniqueDigits = new Set(digits);
51+
if (uniqueDigits.size < 2) {
52+
return false;
53+
}
54+
55+
// Requirement Rule 3: The final digit must be even
56+
const lastDigit = digits[digits.length - 1];
57+
if (lastDigit % 2 !== 0) {
58+
return false;
59+
}
60+
61+
// Requirement Rule 4: The sum of all digits must be greater than 16
62+
const totalSum = digits.reduce((sum, currentDigit) => sum + currentDigit, 0);
63+
if (totalSum <= 16) {
64+
return false;
65+
}
66+
67+
// If the number passes every single gatekeeper conditional check above, it's valid!
68+
return true;
69+
}
70+
71+
module.exports = validateCreditCard;

0 commit comments

Comments
 (0)