Javascript IBAN validator displaying failure reasons
1 min readFeb 21, 2024
If you need a Javascript library to validate IBAN bank numbers, ibantools seems the most updated and stable library at the moment.
In case of validation errors, it returns error codes that internally have a meaning.
If you need to display in the logs the error names (e.g. WrongBBANLengt/WrongBBANFormat/WrongIBANChecksum
) instead of the numeric code, you can use this code that wraps and rethrow the errors with their corresponding name.
import * as ibantools from 'ibantools';
import { ValidationErrorsIBAN } from 'ibantools';
import { BadRequestError } from '../exceptions/BadRequestError.js';
/**
* @param {string} iban
* @returns {boolean}
*
* @throws BadRequestError
*/
export const validateIBAN = (iban) => {
let result = {};
try {
result = ibantools.validateIBAN(iban);
console.log(`iban ${iban} valid`);
} catch (error) {
throw new BadRequestError(`Invalid IBAN, ${error}`);
}
if (!result.valid) {
const errorsCsv = result.errorCodes.map(code => ValidationErrorsIBAN[code]).join(', ');
throw new BadRequestError(`Invalid IBAN, ${errorsCsv}`);
}
return true;
};
And this is the unit test
import { validateIBAN } from 'ibanValidator.js';
describe('isIBANValid', () => {
test.each([
{ iban: 'BE68539007547034', expectedResult: true },
// add more here ....
// invalid ones
{ iban: 'invalid iban', expectedResult: false, expectedError: 'Invalid IBAN, NoIBANCountry' },
{ iban: 'AAAA088110105031K002U', expectedResult: false, expectedError: 'Invalid IBAN, NoIBANCountry' },
{
iban: 'LI31088110105031K001G1',
expectedResult: false,
expectedError: 'Invalid IBAN, WrongBBANLength, WrongBBANFormat, WrongIBANChecksum',
},
])(
'returns $expectedResult for IBAN $iban',
({ iban, expectedResult, expectedError }) => {
if (expectedResult) {
expect(validateIBAN(iban)).toBe(true);
} else {
expect(() => validateIBAN(iban)).toThrowError(expectedError);
}
},
);
});