IBAN Validator Swift

时间:2017-05-05 11:35:11

标签: ios swift iban

我正在编写一个算法来验证Swift 3中的IBAN(国际银行帐号)并且无法确定其中一个验证。

示例IBAN - BE68539007547034

以下是验证规则 -

  1. 输入数字的长度应为16。
  2. 前2个字符是国家/地区代码(非数字)。
  3. 最后14个是数字。
  4. 最后2个字符是前12个数字字符的模97结果。
  5. 虽然#1 - #3很清楚,但我需要清楚#4。如果有人之前已经这样做并知道它,请告诉我。

4 个答案:

答案 0 :(得分:10)

如果您按照wikipedia上的算法:

,验证算法会非常简单
extension String {
    private func mod97() -> Int {
        let symbols: [Character] = Array(self)
        let swapped = symbols.dropFirst(4) + symbols.prefix(4)

        let mod: Int = swapped.reduce(0) { (previousMod, char) in
            let value = Int(String(char), radix: 36)! // "0" => 0, "A" => 10, "Z" => 35
            let factor = value < 10 ? 10 : 100          
            return (factor * previousMod + value) % 97
        }

        return mod
    }    

    func passesMod97Check() -> Bool {
        guard self.characters.count >= 4 else {
            return false
        }

        let uppercase = self.uppercased()

        guard uppercase.range(of: "^[0-9A-Z]*$", options: .regularExpression) != nil else {
            return false
        }

        return (uppercase.mod97() == 1)
    }
}

用法:

let iban = "XX0000000..."
let valid = iban.passesMod97Check()

如果要验证特定国家/地区的格式,只需修改正则表达式,例如

"^[A-Z]{2}[0-9]{14}$"

或直接

"^BE\\d{14}$"

答案 1 :(得分:7)

来自Wikipedia

let IBAN = "GB82WEST12345698765432" // uppercase, no whitespace !!!!
var a = IBAN.utf8.map{ $0 }
while a.count < 4 {
    a.append(0)
}
let b = a[4..<a.count] + a[0..<4]
let c = b.reduce(0) { (r, u) -> Int in
    let i = Int(u)
    return i > 64 ? (100 * r + i - 55) % 97: (10 * r + i - 48) % 97
}
print( "IBAN \(IBAN) is", c == 1 ? "valid": "invalid")

打印

IBAN GB82WEST12345698765432 is valid

使用你问题的IBAN打印

IBAN BE68539007547034 is valid

答案 2 :(得分:-1)

我在Objective-C中找到了一个适合我的解决方案 https://gist.github.com/0xc010d/5301790您可以为Swift重写或使用桥接标头。 mod97 IBAN检查算法的Objective-C实现

#import <Foundation/Foundation.h>

@interface NSString (Mod97Check)

- (BOOL)passesMod97Check; // Returns result of mod 97 checking algorithm. Might be used to check IBAN.
                          // Expects string to contain digits and/or upper-/lowercase letters; space and all the rest symbols are not acceptable.

@end
#import "NSString+Mod97Check.h"

@implementation NSString (Mod97Check)

- (BOOL)passesMod97Check {
    NSString *string = [self uppercaseString];
    NSInteger mod = 0, length = [self length];
    for (NSInteger index = 4; index < length + 4; index ++) {
        unichar character = [string characterAtIndex:index % length];
        if (character >= '0' && character <= '9') {
            mod = (10 * mod + (character - '0')) % 97; // '0'=>0, '1'=>1, ..., '9'=>9
        }
        else if (character >= 'A' && character <= 'Z') {
            mod = (100 * mod + (character - 'A' + 10)) % 97; // 'A'=>10, 'B'=>11, ..., 'Z'=>35
        }
        else {
            return NO;
        }
    }
    return (mod == 1);
}

@end
-(BOOL)isValidIBAN {
    NSString *iban = self;
    static NSString* const LettersAndDecimals = @"ABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789";
    iban = [[iban stringByReplacingOccurrencesOfString:@" " withString:@""] uppercaseString];
    NSCharacterSet *invalidChars = [[NSCharacterSet characterSetWithCharactersInString:LettersAndDecimals] invertedSet];

    if ([iban rangeOfCharacterFromSet:invalidChars].location != NSNotFound)
    {
        return NO;
    }

    int checkDigit = [iban substringWithRange:NSMakeRange(2, 2)].intValue;
    iban = [NSString stringWithFormat:@"%@%@",[iban substringWithRange:NSMakeRange(4, iban.length - 4)], [iban substringWithRange:NSMakeRange(0, 4)]] ;

    for (int i = 0; i < iban.length; i++) {
        unichar c = [iban characterAtIndex:i];
        if (c >= 'A' && c <= 'Z') {
            iban = [NSString stringWithFormat:@"%@%d%@", [iban substringWithRange:NSMakeRange(0, i)], (c - 'A' + 10),[iban substringWithRange:NSMakeRange(i+1, iban.length - i - 1)]];
        }

    }
    iban = [[iban substringWithRange:NSMakeRange(0, iban.length - 2)] stringByAppendingString:@"00"];

    while(true)
    {
        int iMin = (int)MIN(iban.length, 9);
        NSString* strPart = [iban substringWithRange:NSMakeRange(0, iMin)];
        int decnumber = strPart.intValue;
        if(decnumber < 97 || iban.length < 3)
            break;
        int del = decnumber % 97;
        iban =  [NSString stringWithFormat:@"%d%@", del, [iban substringFromIndex:iMin]];
    }
    int check = 98 - iban.intValue;

    return checkDigit == check;
}

答案 3 :(得分:-2)

你走了:

func isValidIBAN(text:String) -> Bool {
        let ibanRegEx = "[a-zA-Z]{2}+[0-9]{2}+[a-zA-Z0-9]{4}+[0-9]{7}([a-zA-Z0-9]?){0,16}"
        let ibanTest = NSPredicate(format:"SELF MATCHES %@", ibanRegEx)
        return ibanTest.evaluate(with: text)
    }

很干净,而且很有效。