|
| 1 | +// |
| 2 | +// Validator |
| 3 | +// Copyright © 2025 Space Code. All rights reserved. |
| 4 | +// |
| 5 | + |
| 6 | +/// Validates that a string is a valid IBAN (International Bank Account Number). |
| 7 | +/// |
| 8 | +/// Uses a simplified IBAN validation algorithm: |
| 9 | +/// 1. Checks length according to country code (2 letters + digits) |
| 10 | +/// 2. Moves first 4 characters to the end |
| 11 | +/// 3. Converts letters to numbers (A=10, B=11, ..., Z=35) |
| 12 | +/// 4. Checks if the resulting number mod 97 equals 1 |
| 13 | +/// |
| 14 | +/// # Example: |
| 15 | +/// ```swift |
| 16 | +/// let rule = IBANValidationRule(error: "Invalid IBAN") |
| 17 | +/// rule.validate(input: "GB82WEST12345698765432") // true |
| 18 | +/// rule.validate(input: "INVALIDIBAN") // false |
| 19 | +/// ``` |
| 20 | +public struct IBANValidationRule: IValidationRule { |
| 21 | + // MARK: - Types |
| 22 | + |
| 23 | + public typealias Input = String |
| 24 | + |
| 25 | + // MARK: Properties |
| 26 | + |
| 27 | + /// The validation error returned when validation fails. |
| 28 | + public let error: IValidationError |
| 29 | + |
| 30 | + // MARK: Initialization |
| 31 | + |
| 32 | + /// Creates an IBAN validation rule. |
| 33 | + /// |
| 34 | + /// - Parameter error: The validation error returned if validation fails. |
| 35 | + public init(error: IValidationError) { |
| 36 | + self.error = error |
| 37 | + } |
| 38 | + |
| 39 | + // MARK: IValidationRule |
| 40 | + |
| 41 | + public func validate(input: String) -> Bool { |
| 42 | + let trimmed = input.replacingOccurrences(of: " ", with: "").uppercased() |
| 43 | + guard trimmed.count >= 4 else { return false } |
| 44 | + |
| 45 | + let rearranged = String(trimmed.dropFirst(4) + trimmed.prefix(4)) |
| 46 | + |
| 47 | + var numericString = "" |
| 48 | + for char in rearranged { |
| 49 | + if let digit = char.wholeNumberValue { |
| 50 | + numericString.append(String(digit)) |
| 51 | + } else if let ascii = char.asciiValue, ascii >= 65, ascii <= 90 { |
| 52 | + numericString.append(String(Int(ascii) - 55)) |
| 53 | + } else { |
| 54 | + return false |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + var remainder = 0 |
| 59 | + var chunk = "" |
| 60 | + for char in numericString { |
| 61 | + chunk.append(char) |
| 62 | + if let number = Int(chunk), number >= 97 { |
| 63 | + remainder = number % 97 |
| 64 | + chunk = String(remainder) |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + remainder = (Int(chunk) ?? 0) % 97 |
| 69 | + return remainder == 1 |
| 70 | + } |
| 71 | +} |
0 commit comments