iOS-swift3.0 点滴积累:身份证号码校验

身份证号码校验,server端和app端都可以实现。下面实现swift3.0 校验身份证号码是否合法。用swfit 3.0 的String字符串截取

Swift 3的String有三个方法用于做字符串截取

tr.substring(to: String.Index)
str.substring(from: String.Index)
str.substring(with: Range)

用法示例:

var str = "Hello, World"

//这个方法会从字符串的开始截取到to参数指定的索引
str.substring(to: String.Index)

let index = str.index(str.startIndex, offsetBy: 5)  //索引为从开始偏移5个位置
str.substring(to: index)  // 获取Hello

//这个方法会从from参数指定的索引截取到字符串的末尾
substring(from: String.Index)

let index = str.index(str.startIndex, offsetBy: 7) //索引从开始偏移7个位置
str.substring(from: index)  // 输出World

//这个方法是截取指定的字符串范围,范围由Range指定
str.substring(with: Range)

let start = str.index(str.startIndex, offsetBy: 7)  //索引从开始偏移7个位置
let end = str.index(str.endIndex, offsetBy: -3)   //所有从末尾往回偏移三个位置
let range = start..

校验身份证号码是否合法:

func validateIDCardNumber(sfz: String) -> Bool {
        let value = sfz.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
        var length = 0
        if value == "" {
            return false
        } else {
            length = value.characters.count
            if length != 15 && length != 18 {
                return false
            }
        }
        
        //省份代码
        let arearsArray = ["11","12", "13", "14",  "15", "21",  "22", "23",  "31", "32",  "33", "34",  "35", "36",  "37", "41",  "42", "43",  "44", "45",  "46", "50",  "51", "52",  "53", "54",  "61", "62",  "63", "64",  "65", "71",  "81", "82",  "91"]
        let valueStart2 = value.substring(to: value.index(value.startIndex, offsetBy: 2))
        var arareFlag = false
        if arearsArray.contains(valueStart2) {
            arareFlag = true
        }
        if !arareFlag {
            return false
        }
        var regularExpression = NSRegularExpression()
        
        var numberofMatch = Int()
        var year = 0
        switch (length) {
        case 15:
            year = Int(value.substring(with: value.index(value.startIndex, offsetBy: 5).. 0) {
                return true
            } else {
                return false
            }
            
        case 18:
            year = Int(value.substring(with: value.index(value.startIndex, offsetBy: 6).. 0) {
                
                let s =
                    (Int(value.substring(with: value.startIndex..

你可能感兴趣的:(iOS-swift3.0 点滴积累:身份证号码校验)