import UIKit
class Validate: NSObject {
//邮箱、手机验证
enum ValidatedType {
case Email
case PhoneNumber
}
func ValidateText(validatedType type: ValidatedType, validateString: String) -> Bool {
do {
let pattern: String
if type == ValidatedType.Email {
pattern = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
}
else {
pattern = "^1[0-9]{10}$"
}
let regex: NSRegularExpression = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)
let matches = regex.matchesInString(validateString, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, validateString.characters.count))
return matches.count > 0
}
catch {
return false
}
}
func EmailIsValidated(vStr: String) -> Bool {
return ValidateText(validatedType: ValidatedType.Email, validateString: vStr)
}
func PhoneNumberIsValidated(vStr: String) -> Bool {
return ValidateText(validatedType: ValidatedType.PhoneNumber, validateString: vStr)
}
}
第二种写法:
///邮箱认证判断
func lx_isMailBox() -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let emailTest = NSPredicate.init(format: "SELF MATCHES %@", emailRegex)
return emailTest.evaluateWithObject(self)
}
///手机号判断
func lx_isMobilPhoneNumber() -> Bool {
if self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) != 11 {
return false
}else{
/**
* 移动号段正则表达式
*/
let CM_NUM = "^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$"
/**
* 联通号段正则表达式
*/
let CU_NUM = "^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$"
/**
* 电信号段正则表达式
*/
let CT_NUM = "^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$"
let pred1 = NSPredicate.init(format: "SELF MATCHES %@", CM_NUM)
let isMatch1 = pred1.evaluateWithObject(self)
let pred2 = NSPredicate.init(format: "SELF MATCHES %@", CU_NUM)
let isMatch2 = pred2.evaluateWithObject(self)
let pred3 = NSPredicate.init(format: "SELF MATCHES %@", CT_NUM)
let isMatch3 = pred3.evaluateWithObject(self)
if (isMatch1 || isMatch2 || isMatch3) {
return true;
}
}
return false
}