Dia 40/2019 - Detectar e validar números de cartão de crédito

Desafio #92daysofcode que fiz no final de 2019. Nesse artigo temos o dia 40, mostrando o uso de regex para validações.

Pré-visualização

Código

Começamos com a estrutura do HTML.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Day 40</title>
<style>
*, *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing:border-box; }
html { -webkit-box-sizing:border-box; -moz-box-sizing:border-box; box-sizing:border-box; font-size: 62.5%; }
* { margin: 0; padding: 0; list-style: none; outline: none; }
body { background: #000; color: #fff; font-family: Arial, Helvetica, sans-serif; }
.container { margin: 20px auto; max-width: 800px; text-align: center; width: 100%; }
</style>
<link rel="stylesheet" type="text/css" href="./day-40.css">
</head>
<body>
<div class="container">
<!-- payment -->
</div>
<script src="./day-40.js"></script>
</body>
</html>
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<div class="payment">
<div class="item">
<div class="card">
<div class="card-flip">
<div class="card-front">
<div class="card-chip"></div>
<div class="card-flag" data-js="flagPreview"></div>
<div class="card-number card-text" data-js="numberPreview"></div>
<div class="card-name">
<label class="card-label"></label>
<div class="card-text" data-js="namePreview"></div>
</div>
<div class="card-expiration">
<label class="card-label">Valid Dates</label>
<div class="card-text" data-js="expirationPreview"></div>
</div>
</div>
<div class="card-back">
<div class="card-strip"></div>
<div class="card-flag" data-js="flagPreview"></div>
<div class="card-securityCode">
<label class="card-label"></label>
<div class="card-text" data-js="securityCodePreview"></div>
</div>
</div>
</div>
</div>
</div>
<div class="item">
<form class="form">
<fieldset class="form-fieldset">
<label for="field1" class="form-label">Card Number</label>
<input id="field1" type="text" class="form-field" data-js="formNumber" maxlength="16" />
</fieldset>
<fieldset class="form-fieldset">
<label for="field2" class="form-label">Name</label>
<input id="field2" type="text" class="form-field" data-js="formName" />
</fieldset>
<fieldset class="form-fieldset">
<label class="form-label">Expiration date</label>
<div class="wrapper">
<div class="form-select">
<select class="form-select-tag" data-js="formMonth">
<option></option>
<option>01</option>
<option>02</option>
<option>03</option>
<option>04</option>
<option>05</option>
<option>06</option>
<option>07</option>
<option>08</option>
<option>09</option>
<option>10</option>
<option>11</option>
<option>12</option>
</select>
</div>
<div class="form-select">
<select class="form-select-tag" data-js="formYear">
<option></option>
<option>2016</option>
<option>2017</option>
<option>2018</option>
<option>2019</option>
<option>2020</option>
<option>2021</option>
<option>2022</option>
<option>2023</option>
<option>2024</option>
<option>2025</option>
</select>
</div>
</div>
</fieldset>
<fieldset class="form-fieldset">
<label for="field4" class="form-label">Security Code</label>
<input id="field4" type="text" class="form-field" data-js="formSecurityCode" maxlength="3" />
</fieldset>
<button class="form-submit">submit</button>
</form>
</div>
</div>
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
.payment { display: flex; flex-direction: row; }
.item { width: 50%; }

/* FORM */
.form-fieldset { border: none; padding: 10px 0; position: relative; }

.form-label { display: block; text-transform: uppercase; font-size: 1.2rem; margin-bottom: 5px; font-weight: 700; text-align: left; width: 100%; }

.form-field,
.form-select { border: none; border-radius: 4px; font-size: 1.2rem; height: 35px; line-height: 1; overflow: hidden; padding: 10px; width: 100%; }

.wrapper { display: flex; flex-direction: row; justify-content: space-between; }

.form-select { background: #fff; position: relative; width: 45%; }
.form-select:after {
content: '';
border-top: 8px solid #222;
border-left: 4px solid transparent;
border-right: 4px solid transparent;
position: absolute;
z-index: 2;
top: 14px;
right: 10px;
pointer-events: none;
}
.form-select-tag { -webkit-appearance: none; appearance: none; height: 100%; position: absolute; top: 0; left: 0; width: 100%; }

.form-submit { background: #094563; border: none; color: #fff; cursor: pointer; margin-top: 10px; padding: 10px; text-transform: uppercase; width: 100%; }

.error { background: #ff8696; color: #831827; }
.valid { background: #86ffc2; color: #188326; }

/* CARD */
.card { perspective: 1000; position: relative; left: 0; transform: translateX(0); width: 340px; }
.card:hover .card-flip { transform: rotateY(180deg) }

.card-front,
.card-back {
height: 200px;
border-radius: 8px;
backface-visibility: hidden;
background: #931497;
color: #fff;
position: absolute;
top: 0;
left: 0;
width: 340px;
}

.card-flip { transition: 0.6s; transform-style: preserve-3d; position: relative; }
.card-flag { background-repeat: no-repeat; position: absolute; top: 9px; right: 20px; width: 60px; height: 30px; position: absolute; top: 17px; right: 20px; width: 46px; }

.card-front { z-index: 2; transform: rotateY(0deg); }
.card-back { transform: rotateY(180deg); }
.card-back .card-flag { top: 155px; }

.visa { background-image: url("./sprite.png"); background-position: 0 0; }
.mastercard { background-image: url("./sprite.png"); background-position: 0 -30px; }
.amex { background-image: url("./sprite.png"); background-position: 0 -60px; }
.diners { background-image: url("./sprite.png"); background-position: 0 -90px; }
.unknown { background-image: url("./sprite.png"); background-position: 0 -640px; }

.card-text { background: none; border: none; }

.card-chip {
position: absolute;
width: 60px;
height: 40px;
top: 50%;
left: 20px;
margin-top: -20px;
background: #d1e9f5 ;
border-radius: 8px;
}
.card-chip:before {
border-radius: 4px;
height: 100%;
content: '';
margin: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 100%;
}
.card-strip { background: #1a1a1a; position: absolute; width: 100%; height: 50px; top: 30px; left: 0; }

.card-label { display: block; font-size: 0.6rem; opacity: 0.5; margin-bottom: 4px; text-transform: uppercase; }

.card-number { font-size: 1.2rem; position: absolute; margin: 0 auto; top: 140px; left: 20px; }
.card-expiration { font-size: 1.5rem; margin: 0 auto; position: absolute; top: 140px; left: auto; right: 20px; text-transform: capitalize; text-align: right; }
.card-securityCode {
background: #fff;
border-radius: 5px;
color: #000;
height: 35px;
margin: 0 auto;
position: absolute;
top: 90px;
left: 0;
right: 0;
text-align: right;
padding: 10px;
width: 91%;
}
.card-securityCode .card-label { margin: -25px 0 14px; color: #fff; }
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
// https://www.freeformatter.com/credit-card-number-generator-validator.html
const cards = {
visa: { name: 'Visa', regex: /^4(?:[0-9]{11}|[0-9]{14})[0-9]$/, predict: /^4[0-9]*$/, maxLength: 16, maskPattern: '9999 9999 9999 9999' },
mastercard: { name: 'Mastercard', regex: /^5[1-5][0-9]{14}$/, predict: /^5[1-5][0-9]*$/, maxLength: 16, maskPattern: '9999 9999 9999 9999' },
amex: { name: 'American Express', regex: /^3[47][0-9]{13}$/, predict: /^3[47][0-9]*$/, maxLength: 15, maskPattern: '9999 999999 99999' },
diners: { name: 'Diners Club', regex: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/, predict: /^3(?:0[0-5]|[68][0-9])[0-9]*/, maxLength: 14, maskPattern: '9999 9999 9999 9999' },
};

const rules = {
CardNumber: /^([0-9]{8,19})$/,
};

class Validator {
constructor(config) {
const newConfig = config || {};

this.cards = newConfig.cards || {};
this.rules = newConfig.rules || {};

this.errorMessage = newConfig.errorMessage || 'Inválido';

this.cardNumber = newConfig.cardNumber || document.querySelector('[data-js="formNumber"]');
// this.formName = newConfig.formName || document.querySelector('[data-js="formName"]');
// this.formMonth = newConfig.formMonth || document.querySelector('[data-js="formMonth"]');
// this.formYear = newConfig.formYear || document.querySelector('[data-js="formYear"]');
// this.formCCV = newConfig.formCCV || document.querySelector('[data-js="formCCV"]');

this.flag = newConfig.flag || document.querySelectorAll('[data-js="flagPreview"]');
this.numberPreview = newConfig.numberPreview || document.querySelector('[data-js="numberPreview"]');
// this.namePreview = newConfig.namePreview || document.querySelector('[data-js="namePreview"]');
// this.expirationPreview = newConfig.expirationPreview || document.querySelector('[data-js="expirationPreview"]');
// this.securityCodePreview = newConfig.securityCodePreview || document.querySelector('[data-js="securityCodePreview"]');

this.validate();
}

getMask(str, pattern) {
const items = [...pattern];
const noSpaces = [...str.replace(/\s/g, '')];
const masked = [];

items.forEach((value, i) => {
if (noSpaces.length === 0) return;
if (value !== ' ') { masked.push(noSpaces.shift()); }
if (value === ' ') { masked.push(' '); }
});

return masked.join('');
};

getFlag(element) {
let flag = '';
const cardNumber = this.removeSpaces(element.value);

if (!cardNumber) return false;

for (let card in this.cards) {
if (this.cards.hasOwnProperty(card)) {
if (this.cards[card].predict.test(cardNumber)) {
element.setAttribute('mask', this.cards[card].maskPattern);

const maxLength = this.cards[card].maskPattern.length;
this.setMaxlength(element, maxLength);

flag = card;
break;
}
}
}
return flag;
}

setFlagClass(card) {
this.flag.forEach(item => {
item.className = 'card-flag';
card ? item.classList.add(card) : item.classList.add('unkown');
});
};

validateNumber(cardNumber) {
const cNumber = this.removeSpaces(cardNumber);

if (!this.rules.CardNumber.test(cNumber)) {
return false;
}

for (let card in this.cards) {
if (this.cards[card].regex.test(cNumber)) {
return this.validateLuhn(cNumber) ? card : false;
}
}
}

// http://www.datagenetics.com/blog/july42013/index.html
validateLuhn(number) {
const digits = number.split('').reverse();
const oddDigits = [];
const evenDigits = [];

digits.forEach((digit, index) => {
if ((index + 1) % 2 !== 0) {
oddDigits.push(digit);
} else {
evenDigits.push(digit);
}
});

const solution1 = oddDigits.reduce((sum, value) => parseInt(sum) + parseInt(value));
const solution2 = evenDigits.map(digit => {
const multiplication = digit * 2;
if (multiplication > 9) {
const separatedDigits = multiplication.toString().split('');
return ( parseInt(separatedDigits[0]) + parseInt(separatedDigits[1]) );
}
return multiplication;
}).reduce((sum, value) => parseInt(sum) + parseInt(value));

const result = (solution1 + solution2).toString();

if (result.charAt(result.length - 1) === '0') {
return true;
}
}

validCardClass(element, valid) {
if (!element) return;
if (valid) {
element.classList.remove('error');
element.classList.add('valid');
} else {
element.classList.add('error');
element.classList.remove('valid');
}
}

removeSpaces(str) {
return str.replace(/\s/g, '').trim();
}

setMaxlength(element, length) {
element.setAttribute('maxlength', length);
}

validate() {
if (this.cardNumber && this.flag) {
this.cardNumber.addEventListener('input', (evt) => {
evt.target.classList.remove('error');

const mask = evt.target.getAttribute('mask');
if (mask) {
evt.target.value = this.getMask(evt.target.value, mask);
}

// preview
this.numberPreview.innerHTML = evt.target.value;

const card = this.getFlag(evt.target);
this.setFlagClass(card);

if (evt.target.value.length === 0) debugger;

this.validateNumber(evt.target.value) && evt.target.value.length > 0 ? this.validCardClass(this.cardNumber, true) : this.validCardClass(this.cardNumber, false);
});
}
};
}

new Validator({ cards, rules });

// https://www.4devs.com.br/gerador_de_numero_cartao_credito
//
// mastercard 5140494381575369
// visa 4929576464410439
// amex 377390083435438
// diners 36552009688241

Conclusão

A postagem original pode ser vista no meu Instagram e o código está acessível no meu Github.

Relacionados

Ao fechar este aviso ou continuar navegando no site Nerd Calistênico, você aceita o uso de cookies.

Este site usa cookies para assegurar a melhor experiência para os nossos usuários. Consulte nossa política de privacidade.

Uma nova versão está disponível. Clique aqui para atualizar.