-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
50 lines (41 loc) · 1.24 KB
/
script.js
File metadata and controls
50 lines (41 loc) · 1.24 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
const submitBtn = document.getElementById("submit");
submitBtn.addEventListener("click", handleFormSubmit);
function handleFormSubmit(event) {
event.preventDefault();
const month = document.getElementById("month").value;
const year = document.getElementById("year").value;
if (new Date() > new Date(year, month)) {
window.alert("Your card is expired!");
return;
}
const cvv = document.getElementById("cvv").value;
if (!/^[0-9]{3,4}$/.test(cvv)) {
window.alert("Invalid CVV. It must be 3 or 4 digits!");
return;
}
const cnumber = document.getElementById("cnumber").value;
if (!/^[0-9]{13,16}$/.test(cnumber) || !isValid(cnumber)) {
window.alert("Invalid card number!");
return;
}
window.alert("Thanks for the payment!");
}
function isValid(cnumber) {
let arr = cnumber
.split("")
.reverse()
.map((element) => parseInt(element));
const sum = arr.reduce(reducer, 0);
function reducer(accumulator, currentValue, currentIndex) {
currentIndex += 1; // account for 0-based indexing
if (currentIndex % 2 === 0) {
// even index
currentValue *= 2;
if (currentValue > 9) {
currentValue -= 9;
}
}
return accumulator + currentValue;
}
return sum % 10 === 0;
}