Skip to content

Commit 2c78286

Browse files
committed
Add the swiss IBAN to check now must be in one of the two defined formats
1 parent 86335ef commit 2c78286

File tree

2 files changed

+16
-14
lines changed

2 files changed

+16
-14
lines changed

src/lib/string.spec.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,11 +125,12 @@ describe("string tests", () => {
125125
[null as unknown as string, false],
126126
[undefined as unknown as string, false],
127127
["CH9300762011623852957", true],
128+
["CH93 0076 2011 6238 5295 7", true],
129+
["CH93-0076-2011-6238-5295-7", false],
128130
["CH93 0000 0000 0000 0000 1", false],
129131
["ch93 0076 2011 6238 5295 7", false],
130132
["DE93 0076 2011 6238 5295 7", false],
131-
["CH93 0076 2011 6238 5295 7", true],
132-
])("Is Swiss IBAN valid", (unformattedIbanNumber, expected) => {
133+
])("check if this swiss IBAN is valid or not", (unformattedIbanNumber, expected) => {
133134
expect(isValidSwissIbanNumber(unformattedIbanNumber)).toBe(expected);
134135
});
135136
});

src/lib/string.ts

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -66,27 +66,28 @@ export function truncate(value: string | undefined, maxLength: number, suffix =
6666
}
6767

6868
/**
69-
* Checks if the provided string is a valid Swiss IBAN number
69+
* Checks if the provided string is a valid swiss IBAN number
7070
* @param ibanNumber The provided IBAN number to check
71+
* Must be in one of the following formats:
72+
* - "CHXX XXXX XXXX XXXX XXXX X" with whitespaces
73+
* - "CHXXXXXXXXXXXXXXXXXXX" without whitespaces
7174
* @returns The result of the IBAN number check
7275
*/
7376
export function isValidSwissIbanNumber(ibanNumber: string): boolean {
7477
if (isNullOrWhitespace(ibanNumber)) {
7578
return false;
7679
}
77-
const compactIban = ibanNumber.replaceAll(/\s+/g, "");
78-
if (!/^CH\d{19}$/.test(compactIban)) {
80+
81+
const compactIbanNumberWithWhiteSpaces = new RegExp(/^CH\d{2}(?:\s?\d{4}){4}\s?\d{1}$/);
82+
const compactIbanNumberWithoutWhiteSpaces = new RegExp(/^CH\d{19}$/);
83+
84+
if (!compactIbanNumberWithWhiteSpaces.test(ibanNumber) && !compactIbanNumberWithoutWhiteSpaces.test(ibanNumber)) {
7985
return false;
8086
}
81-
const rearrangedIban = compactIban.slice(4) + compactIban.slice(0, 4);
82-
const numericStr = Array.from(rearrangedIban, (ch) => {
83-
if (/[A-Z]/.test(ch)) {
84-
const code = ch.codePointAt(0);
85-
// code is never undefined!
86-
return (code! - 55).toString();
87-
}
88-
return ch;
89-
}).join("");
87+
88+
const compactInsuranceNumber = ibanNumber.replaceAll(/[\s.]+/g, "");
89+
const rearrangedIban = compactInsuranceNumber.slice(4) + compactInsuranceNumber.slice(0, 4);
90+
const numericStr = rearrangedIban.replaceAll(/[A-Z]/g, (ch) => (ch.codePointAt(0)! - 55).toString());
9091

9192
let restOfCalculation = 0;
9293
for (const digit of numericStr) {

0 commit comments

Comments
 (0)