-
Notifications
You must be signed in to change notification settings - Fork 2
/
br-cnpj-validator.html
51 lines (49 loc) · 1.52 KB
/
br-cnpj-validator.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
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../iron-validator-behavior/iron-validator-behavior.html">
<script>
Polymer({
is: 'br-cnpj-validator',
behaviors: [
Polymer.IronValidatorBehavior
],
validate: function(value) {
var stripped = (value || "").toString().replace(/[-\/.]/g, "");
// CNPJ must be defined
if (!stripped) return false;
// CNPJ must have 14 chars
if (stripped.length !== 14) return false;
// CNPJ can't be blacklisted
if (this._blacklist.indexOf(stripped) >= 0) return false;
var numbers = stripped.substr(0, 12);
numbers += this._verifierDigit(numbers);
numbers += this._verifierDigit(numbers);
return numbers.substr(-2) === stripped.substr(-2);
},
_verifierDigit: function (numbers) {
var index = 2;
var reverse = numbers.split("").reduce(function(buffer, number) {
return [parseInt(number, 10)].concat(buffer);
}, []);
var sum = reverse.reduce(function(buffer, number) {
buffer += number * index;
index = (index === 9 ? 2 : index + 1);
return buffer;
}, 0);
var mod = sum % 11;
return (mod < 2 ? 0 : 11 - mod);
},
// Blacklist common values.
_blacklist: [
"00000000000000",
"11111111111111",
"22222222222222",
"33333333333333",
"44444444444444",
"55555555555555",
"66666666666666",
"77777777777777",
"88888888888888",
"99999999999999"
]
});
</script>