forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidateCreditCard.js
More file actions
Latest commit
63 lines (56 loc) · 2.08 KB
/
Copy pathValidateCreditCard.js
File metadata and controls
63 lines (56 loc) · 2.08 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* Validate a given credit card number
*
* The core of the validation of credit card numbers is the Luhn algorithm.
*
* The validation sum should be completely divisible by 10 which is calculated as follows,
* every first digit is added directly to the validation sum.
* For every second digit in the credit card number, the digit is multiplied by 2.
* If the product is greater than 10 the digits of the product are added.
* This resultant digit is considered for the validation sum rather than the digit itself.
*
* Ref: https://www.geeksforgeeks.org/luhn-algorithm/
*/
constluhnValidation=(creditCardNumber)=>{
letvalidationSum=0
creditCardNumber.split('').forEach((digit,index)=>{
letcurrentDigit=parseInt(digit)
if(index%2===0){
// Multiply every 2nd digit from the left by 2
currentDigit*=2
// if product is greater than 10 add the individual digits of the product to get a single digit
if(currentDigit>9){
currentDigit%=10
currentDigit+=1
}
}
validationSum+=currentDigit
})
returnvalidationSum%10===0
}
constvalidateCreditCard=(creditCardString)=>{
constvalidStartSubString=['4','5','6','37','34','35']// Valid credit card numbers start with these numbers
if(typeofcreditCardString!=='string'){
thrownewTypeError('The given value is not a string')
}
consterrorMessage=`${creditCardString} is an invalid credit card number because `
if(isNaN(creditCardString)){
thrownewTypeError(errorMessage+'it has nonnumerical characters.')
}
constcreditCardStringLength=creditCardString.length
if(!(creditCardStringLength>=13&&creditCardStringLength<=16)){
thrownewError(errorMessage+'of its length.')
}
if(
!validStartSubString.some((subString)=>
creditCardString.startsWith(subString)
)
){
thrownewError(errorMessage+'of its first two digits.')
}
if(!luhnValidation(creditCardString)){
thrownewError(errorMessage+'it fails the Luhn check.')
}
returntrue
}
export{validateCreditCard}