@@ -65,6 +65,51 @@ export function truncate(value: string | undefined, maxLength: number, suffix =
6565 return `${ value . slice ( 0 , maxLength ) } ${ suffix } ` ;
6666}
6767
68+ /**
69+ * Checks if the provided string is a valid swiss IBAN number
70+ * @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
74+ * @returns The result of the IBAN number check
75+ */
76+ export function isValidSwissIbanNumber ( ibanNumber : string ) : boolean {
77+ // 1. Reject null, undefined or whitespace-only strings
78+ if ( isNullOrWhitespace ( ibanNumber ) ) {
79+ return false ;
80+ }
81+
82+ // 2. Define allowed strict formats
83+ // - with spaces: "CHXX XXXX XXXX XXXX XXXX X"
84+ const compactIbanNumberWithWhiteSpaces = new RegExp ( / ^ C H \d { 2 } (?: \d { 4 } ) { 4 } \d { 1 } $ / ) ;
85+ // - without spaces: "CHXXXXXXXXXXXXXXXXXXX"
86+ const compactIbanNumberWithoutWhiteSpaces = new RegExp ( / ^ C H \d { 19 } $ / ) ;
87+
88+ // 3. Check if input matches one of the allowed formats
89+ if ( ! compactIbanNumberWithWhiteSpaces . test ( ibanNumber ) && ! compactIbanNumberWithoutWhiteSpaces . test ( ibanNumber ) ) {
90+ return false ;
91+ }
92+
93+ // 4. Remove all spaces to get a compact IBAN string
94+ const compactIbanNumber = ibanNumber . replaceAll ( " " , "" ) ;
95+
96+ // 5. Rearrange IBAN for checksum calculation
97+ // - move first 4 characters (CH + 2 check digits) to the end
98+ const rearrangedIban = compactIbanNumber . slice ( 4 ) + compactIbanNumber . slice ( 0 , 4 ) ;
99+
100+ // 6. Replace letters with numbers (A=10, B=11, ..., Z=35)
101+ const numericStr = rearrangedIban . replaceAll ( / [ A - Z ] / g, ( ch ) => ( ch . codePointAt ( 0 ) ! - 55 ) . toString ( ) ) ;
102+
103+ // 7. Perform modulo 97 calculation to validate IBAN
104+ let restOfCalculation = 0 ;
105+ for ( const digit of numericStr ) {
106+ restOfCalculation = ( restOfCalculation * 10 + Number ( digit ) ) % 97 ;
107+ }
108+
109+ // 8. IBAN is valid only if the remainder equals 1
110+ return restOfCalculation === 1 ;
111+ }
112+
68113/**
69114 * Validation of social insurance number with checking the checksum
70115 * Validation according to https://www.sozialversicherungsnummer.ch/aufbau-neu.htm
0 commit comments