forked from passatgt/hu-bank-account-validator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (63 loc) · 2.3 KB
/
index.js
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
const validBankCodes = require('./assets/validBankCodes');
function validateBankAccount(bankAccountNumber) {
//Remove all non-digit characters.
bankAccountNumber = bankAccountNumber.replace(/\D/g, '');
//Check the length.
if (bankAccountNumber.length !== 16 && bankAccountNumber.length !== 24) {
return false;
}
//Append trailing zeros if the bank account number is only 16 digits long.
if (bankAccountNumber.length === 16) {
bankAccountNumber += '00000000';
}
//Check if the first three digits of the bank account number are a valid bank code.
const bankCode = parseInt(bankAccountNumber.slice(0, 3), 10);
if (!validBankCodes[bankCode]) {
return false;
}
//Split the bank account number into its parts.
const firstPart = bankAccountNumber.slice(0, 8);
const secondPart = bankAccountNumber.slice(8, 24);
//Validate the check digits.
const parts = [firstPart, secondPart];
const weights = [9, 7, 3, 1, 9, 7, 3, 1, 9, 7, 3, 1, 9, 7, 3, 1];
for (let part of parts) {
let digits = part.toString().split('');
digits = digits.map(Number)
//Loop through the digits
let sum = 0;
for (let i = 0; i < digits.length; i++) {
sum += digits[i] * weights[i];
}
//Check if sum can be divided by 10
if(sum % 10 != 0) {
return false;
}
}
//Insert hyphens.
let formattedNumber = bankAccountNumber.replace(/(\d{8})(\d{8})(\d{8})/, '$1-$2-$3');
//If the bank account number is valid, return the name of the bank and the BIC code
return {
bic: validBankCodes[bankCode].bicCode,
name: validBankCodes[bankCode].bankName,
number: formattedNumber,
iban: calculateIBAN(bankAccountNumber)
};
}
function calculateIBAN(bankAccountNumber) {
//Rearrange for checksum calculation
const countryCode = 'HU';
const placeholders = '00';
const rearranged = bankAccountNumber + convertLettersToNumbers(countryCode) + placeholders;
//Convert rearranged string to BigInt
const rearrangedBigInt = BigInt(rearranged);
//Compute Mod-97 checksum
const checksum = 98n - (rearrangedBigInt % 97n);
//Format IBAN
const checkDigits = checksum.toString().padStart(2, '0'); //Always 2 digits
return `${countryCode}${checkDigits}${bankAccountNumber}`;
}
function convertLettersToNumbers(input) {
return input.split('').map(char => char.charCodeAt(0) - 55).join('');
}
module.exports = validateBankAccount;