Swift - 邮箱、手机号码、车牌号等正则判断
2017-03-23 本文已影响93人
yuanweiphone
邮箱、手机号码、车牌号等正则判断
enum Validate {
case email(_: String) // 邮箱
case phoneNumber(_: String) // 手机号
case userName(_: String) // 用户名
case password(_: String) // 密码
case nickName(_: String) // 昵称
case postalCode(_:String) // 邮编
case URL(_: String) // URL
case IP(_: String) // IP
case isChinese(_: String) // 是否全是中文字符
case idNumber(_: String) // 身份证号
var isRight: Bool {
var predicateStr:String!
var currentObject:String!
switch self {
case let .email(str):
predicateStr = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
currentObject = str
case let .phoneNumber(str):
predicateStr = "^((1[34578][0-9]{9})|((0\\d{2}-\\d{8})|(0\\d{3}-\\d{7,8})|(0\\d{10,11}))$"
currentObject = str
case let .userName(str):
predicateStr = "^([\\u4E00-\\u9FA5A-Za-z0-9_]{2,10}$)"
currentObject = str
case let .postalCode(str):
predicateStr = "^[0-8]\\d{5}(?!\\d)$"
currentObject = str
case let .password(str):
predicateStr = "^[a-zA-Z0-9]{6,20}+$"
currentObject = str
case let .nickName(str):
predicateStr = "^([\\u4E00-\\u9FA5A-Za-z0-9_]{2,10}$)"
currentObject = str
case let .URL(str):
predicateStr = "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$"
currentObject = str
case let .IP(str):
predicateStr = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
currentObject = str
case let . isChinese(str):
predicateStr = "(^[\u{4e00}-\u{9fa5}]$)"
currentObject = str
case let . idNumber(str):
predicateStr = "(^[0-9]{15}$)|([0-9]{17}([0-9]|[xX])$)"
currentObject = str
}
let predicate = NSPredicate(format: "SELF MATCHES %@" ,predicateStr)
return predicate.evaluate(with: currentObject)
}
}
使用方法
Validate.email("test@163.com").isRight