1、简介
在App开发中,涉及到用户登录时,我们经常需要检验用户输入的账户是否是我们指定的类型。例如判断用户的账号是不是正确的手机号、邮箱等。
2、实现
在Swift里我们可以通过如下代码轻松的实现字段串相关类型的判断
import Foundation
extension String {
func isvalitemobile() -> Bool {
let mobileRegex = "^((13[0-9])|(15[^4,\\D])|(18[0,0-9])|(17[0,0-9]))\\d{8}$"
let mobileTest:NSPredicate = NSPredicate(format: "SELF MATCHES %@", mobileRegex)
return mobileTest.evaluate(with: self)
}
func isvaliteemail() -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let emailTest:NSPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
return emailTest.evaluate(with: self)
}
func isvaliteidnum() -> Bool {
let idRegex = "^(\\d{14}|\\d{17})(\\d|[xX])$"
let idTest:NSPredicate = NSPredicate(format: "SELF MATCHES %@", idRegex)
return idTest.evaluate(with: self)
}
}