/*!
验证身份证
- returns: true/false
*/
func chk18PaperId() -> Bool {
//判断位数
if self.length != 15 && self.length != 18 {
return false
}
var carid = self
var lSumQT = 0
//加权因子
let R = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
//校验码
let sChecker: [Int8] = [49,48,88, 57, 56, 55, 54, 53, 52, 51, 50]
//将15位身份证号转换成18位
let mString = NSMutableString.init(string: self)
if self.length == 15 {
mString.insertString("19", atIndex: 6)
var p = 0
let pid = mString.UTF8String
for i in 0...16 {
p += (pid[i]-48) * R[i]
}
let o = p % 11
let stringContent = NSString(format: "%c", sChecker[o])
mString.insertString(stringContent as String, atIndex: mString.length)
carid = mString
}
//判断年月日是否有效
//年份
let strYear = Int(carid.substringWithRange(NSMakeRange(6, 4)))
//月份
let strMonth = Int(carid.substringWithRange(NSMakeRange(10, 2)))
//日
let strDay = Int(carid.substringWithRange(NSMakeRange(12, 2)))
let localZone = NSTimeZone.localTimeZone()
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .NoStyle
dateFormatter.timeZone = localZone
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFormatter.dateFromString("\(String(format: "%02d",strYear!))-\(String(format: "%02d",strMonth!))-\(String(format: "%02d",strDay!)) 12:01:01")
if date == nil {
return false
}
let paperId = carid.UTF8String
//检验长度
if 18 != carid.length {
return false
}
//校验数字
func isDigit(c: Int8) -> Bool {
return 0 <= c && c <= 9
}
for i in 0...18 {
if isDigit(paperId[i]) && !(88 == paperId[i] || 120 == paperId[i]) && 17 == i {
return false
}
}
//验证最末的校验码
for i in 0...16 {
lSumQT += (paperId[i]-48) * R[i]
}
if sChecker[lSumQT%11] != paperId[17] {
return false
}
return true
}
网友评论