电子邮件和 Phone 在 Swift 中验证
Email & Phone Validation in Swift
我正在使用以下代码进行 phone 号码验证。但我收到以下错误。我无法继续进行。帮助我们推进它。
class PhoneNumberValidation: Validation {
let PHONE_REGEX = "^\d{3}-\d{3}-\d{4}$"
func validate(value: String) -> (Bool, ValidationErrorType) {
if let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX) {
if phoneTest.evaluateWithObject(value) {
return (true, .NoError)
}
return (false, .PhoneNumber)
}
return (false, .PhoneNumber)
}
}
错误:swift:15:28:条件绑定中的绑定值必须是可选类型
是的,您的错误在 XCode 6.1
下方
发生此错误是因为 if
条件必须 Bool
return 类型,但在您的 if 条件 Return 类型中是 NSPredicate
以便你得到错误 swift: 条件绑定中的绑定值必须是可选类型 你可以按下面的方式解决。
var phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
if phoneTest.evaluateWithObject(value) {
return (true, .NoError)
}
return (false, .PhoneNumber)
}
Email-Validations 在 Swift.
func isValidEmail(testStr:String) -> Bool {
print("validate emilId: \(testStr)")
let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\t| )*\r\n)?(?:\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+(?:\.[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\[|\])|(?:\\(?:\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)(?:\.[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)*)|(?:\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\.){3}(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\])))(?:(?:(?:(?: )*(?:(?:(?:\t| )*\r\n)?(?:\t| )+))+(?: )*)|(?: )+)?$"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
let result = emailTest.evaluateWithObject(testStr)
return result
}
使用Email-validation:
if isValidEmail("kirit@gmail.com"){
print("Validate EmailID")
}
else{
print("invalide EmailID")
}
Phone-Number 在 Swift
中验证
func validate(value: String) -> Bool {
let PHONE_REGEX = "^\d{3}-\d{3}-\d{4}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluate(with: value)
return result
}
以下代码适用于 xcode 6.3 beta
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}"
let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch)
let result = range != nil ? true : false
return result
}
使用方法:
例如。
if isValidEmail(email.text) == false{
//your code here
}
Swift 3.0 到 5.0 更新的解决方案:
//MARK: - Validation Extension
extension String {
//To check text field or String is blank or not
var isBlank: Bool {
get {
let trimmed = trimmingCharacters(in: CharacterSet.whitespaces)
return trimmed.isEmpty
}
}
//Validate Email
var isEmail: Bool {
do {
let regex = try NSRegularExpression(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", options: .caseInsensitive)
return regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.count)) != nil
} catch {
return false
}
}
var isAlphanumeric: Bool {
return !isEmpty && range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil
}
//validate Password
var isValidPassword: Bool {
do {
let regex = try NSRegularExpression(pattern: "^[a-zA-Z_0-9\-_,;.:#+*?=!§$%&/()@]+$", options: .caseInsensitive)
if(regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil){
if(self.characters.count>=6 && self.count<=20){
return true
}else{
return false
}
}else{
return false
}
} catch {
return false
}
}
}
使用电子邮件验证:
if(txtEmail.isEmail) {
}
Swift 2.0 解
将这些行粘贴到代码中的任意位置。(或在您的 Constant 文件中)
extension String {
//To check text field or String is blank or not
var isBlank: Bool {
get {
let trimmed = stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
return trimmed.isEmpty
}
}
//Validate Email
var isEmail: Bool {
do {
let regex = try NSRegularExpression(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", options: .CaseInsensitive)
return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.count)) != nil
} catch {
return false
}
}
//validate PhoneNumber
var isPhoneNumber: Bool {
let charcter = NSCharacterSet(charactersInString: "+0123456789").invertedSet
var filtered:NSString!
let inputString:NSArray = self.componentsSeparatedByCharactersInSet(charcter)
filtered = inputString.componentsJoinedByString("")
return self == filtered
}
}
File-New-File。制作一个 Swift class 命名为 AppExtension.Add 如下。
extension UIViewController{
func validateEmailAndGetBoolValue(candidate: String) -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}"
return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluateWithObject(candidate)
}
}
Use:
var emailValidator:Bool?
self.emailValidator = self.validateEmailAndGetBoolValue(resetEmail!)
print("emailValidator : "+String(self.emailValidator?.boolValue))
Use a loop to alternate desired results.
OR
extension String
{
//Validate Email
var isEmail: Bool {
do {
let regex = try NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .CaseInsensitive)
return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
} catch {
return false
}
}
}
Use:
if(resetEmail!.isEmail)
{
AppController().requestResetPassword(resetEmail!)
self.view.makeToast(message: "Sending OTP")
}
else
{
self.view.makeToast(message: "Please enter a valid email")
}
另一个为了多样性的解决方案..
public extension String {
public var validPhoneNumber:Bool {
let types:NSTextCheckingType = [.PhoneNumber]
guard let detector = try? NSDataDetector(types: types.rawValue) else { return false }
if let match = detector.matchesInString(self, options: [], range: NSMakeRange(0, characters.count)).first?.phoneNumber {
return match == self
}else{
return false
}
}
}
//and use like so:
if "16465551212".validPhoneNumber {
print("valid phone number")
}
也许 Swift 中更好的 phone 验证器 2:
extension String {
var isPhoneNumber: Bool {
do {
let detector = try NSDataDetector(types: NSTextCheckingType.PhoneNumber.rawValue)
let matches = detector.matchesInString(self, options: [], range: NSMakeRange(0, self.characters.count))
if let res = matches.first {
return res.resultType == .PhoneNumber && res.range.location == 0 && res.range.length == self.characters.count
} else {
return false
}
} catch {
return false
}
}
}
Swift 3:
private func validate(phoneNumber: String) -> Bool {
let charcterSet = NSCharacterSet(charactersIn: "+0123456789").inverted
let inputString = phoneNumber.components(separatedBy: charcterSet)
let filtered = inputString.joined(separator: "")
return phoneNumber == filtered
}
Kirit Modi 关于 Swift 3 的电子邮件验证的回应:
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\t| )*\r\n)?(?:\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+(?:\.[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\[|\])|(?:\\(?:\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)(?:\.[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)*)|(?:\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\.){3}(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\])))(?:(?:(?:(?: )*(?:(?:(?:\t| )*\r\n)?(?:\t| )+))+(?: )*)|(?: )+)?$"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
let result = emailTest.evaluate(with: testStr)
return result
}
Phone 仅适用于 ّIran phone 数字
的正则表达式
func isValidPhone(phone: String) -> Bool {
let PHONE_REGEX = "^09[0-9'@s]{9,9}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluate(with: phone)
return result
}
更新 Swift 3
extension String {
var isPhoneNumber: Bool {
do {
let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue)
let matches = detector.matches(in: self, options: [], range: NSMakeRange(0, self.characters.count))
if let res = matches.first {
return res.resultType == .phoneNumber && res.range.location == 0 && res.range.length == self.characters.count
} else {
return false
}
} catch {
return false
}
}
}
您可以创建单独的 class 进行验证,如下所示:
enum AIValidationRule: Int {
case
EmptyCheck,
MinMaxLength,
FixedLength,
EmailCheck,
UpperCase,
LowerCase,
SpecialCharacter,
DigitCheck,
WhiteSpaces,
None
}
let ValidationManager = AIValidationManager.sharedManager
func validateTextField(txtField:AITextField, forRule rule:AIValidationRule, withMinimumChar minChar:Int, andMaximumChar maxChar:Int) -> (isValid:Bool, errMessage:String, txtFieldWhichFailedValidation:AITextField)? {
switch rule {
case .EmptyCheck:
return (txtField.text?.characters.count == 0) ? (false,"Please enter \(txtField.placeholder!.lowercased())",txtField) : nil
case .MinMaxLength:
return (txtField.text!.characters.count < minChar || txtField.text!.characters.count > maxChar) ? (false,"\(txtField.placeholder!) should be of \(minChar) to \(maxChar) characters",txtField) : nil
case .FixedLength:
return (txtField.text!.characters.count != minChar) ? (false,"\(txtField.placeholder!) should be of \(minChar) characters",txtField) : nil
case .EmailCheck:
return (!(txtField.text?.isValidEmail())!) ? (false,"Please enter valid email",txtField) : nil
case .UpperCase:
return ((txtField.text! as NSString).rangeOfCharacter(from: NSCharacterSet.uppercaseLetters).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one uppercase letter",txtField) : nil
case .LowerCase:
return ((txtField.text! as NSString).rangeOfCharacter(from: NSCharacterSet.lowercaseLetters).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one lowercase letter",txtField) : nil
case .SpecialCharacter:
let symbolCharacterSet = NSMutableCharacterSet.symbol()
symbolCharacterSet.formUnion(with: NSCharacterSet.punctuationCharacters)
return ((txtField.text! as NSString).rangeOfCharacter(from: symbolCharacterSet as CharacterSet).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one special letter",txtField) : nil
case .DigitCheck:
return ((txtField.text! as NSString).rangeOfCharacter(from: NSCharacterSet(charactersIn: "0123456789") as CharacterSet).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one digit letter",txtField) : nil
case .WhiteSpaces:
return (txtField.text!.containsAdjacentSpaces() || txtField.text!.isLastCharcterAWhiteSpace()) ? (false,"\(txtField.placeholder!) seems to be invalid",txtField) : nil
case .None:
return nil
}
}
func validateTextField(txtField:AITextField, forRules rules:[AIValidationRule]) -> (isValid:Bool, errMessage:String, txtFieldWhichFailedValidation:AITextField)? {
return validateTextField(txtField: txtField, forRules: rules, withMinimumChar: 0, andMaximumChar: 0)
}
func validateTextField(txtField:AITextField, forRules rules:[AIValidationRule], withMinimumChar minChar:Int, andMaximumChar maxChar:Int) -> (isValid:Bool, errMessage:String, txtFieldWhichFailedValidation:AITextField)? {
var strMessage:String = ""
for eachRule in rules {
if let result = validateTextField(txtField: txtField, forRule: eachRule, withMinimumChar: minChar, andMaximumChar: maxChar) {
if(eachRule == AIValidationRule.EmptyCheck){
return result
}else{
strMessage += "\(strMessage.characters.count == 0 ? "" : "\n\n") \(result.errMessage)"
}
}
}
return strMessage.characters.count > 0 ? (false,strMessage,txtField) : nil
}
使用Swift 3
func validate(value: String) -> Bool {
let PHONE_REGEX = "^\d{3}-\d{3}-\d{4}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluate(with: value)
return result
}
Swift 3
验证电子邮件
class func validateEmail(email: String) -> Bool{
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}"
return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: email)
}
Phone 号码验证
class func validatePhoneNumber(value: String) -> Bool {
let PHONE_REGEX = "^\d{3}-\d{3}-\d{4}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluate(with: value)
return result
}
For Swift 3.0 and above
var isPhoneNumber: Bool{
let allowedCharacters = CharacterSet(charactersIn: "+0123456789").inverted
let inputString = components(separatedBy: allowedCharacters)
let filtered = inputString.joined(separator: "")
return self == filtered}
Updated for Swift :
使用以下代码验证电子邮件、姓名、手机和密码;
// Name validation
func isValidName(_ nameString: String) -> Bool {
var returnValue = true
let mobileRegEx = "[A-Za-z]{2}" // "^[A-Z0-9a-z.-_]{5}$"
do {
let regex = try NSRegularExpression(pattern: mobileRegEx)
let nsString = nameString as NSString
let results = regex.matches(in: nameString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
// password validation
func isValidPassword(_ PasswordString: String) -> Bool {
var returnValue = true
let mobileRegEx = "[A-Za-z0-9.-_@#$!%&*]{5,15}$" // "^[A-Z0-9a-z.-_]{5}$"
do {
let regex = try NSRegularExpression(pattern: mobileRegEx)
let nsString = PasswordString as NSString
let results = regex.matches(in: PasswordString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
// email validaton
func isValidEmailAddress(_ emailAddressString: String) -> Bool {
var returnValue = true
let emailRegEx = "[A-Z0-9a-z.-_]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,3}"
do {
let regex = try NSRegularExpression(pattern: emailRegEx)
let nsString = emailAddressString as NSString
let results = regex.matches(in: emailAddressString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
// mobile no. validation
func isValidPhoneNumber(_ phoneNumberString: String) -> Bool {
var returnValue = true
// let mobileRegEx = "^[789][0-9]{9,11}$"
let mobileRegEx = "^[0-9]{10}$"
do {
let regex = try NSRegularExpression(pattern: mobileRegEx)
let nsString = phoneNumberString as NSString
let results = regex.matches(in: phoneNumberString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
//如何使用?
let isFullNameValid = isValidName("ray")
if isFullNameValid{
print("Valid name...")
}else{
print("Invalid name...")
}
Swift 4.1.
func isValidPhone(phone: String) -> Bool {
let phoneRegex = "^[0-9]{6,14}$";
let valid = NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: phone)
return valid
}
func isValidEmail(candidate: String) -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"
var valid = NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: candidate)
if valid {
valid = !candidate.contains("..")
}
return valid
}
Swift 4.2 和 Xcode 10.1
//For mobile number validation
func isValidPhone(phone: String) -> Bool {
let phoneRegex = "^((0091)|(\+91)|0?)[6789]{1}\d{9}$";
let valid = NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: phone)
return valid
}
//For email validation
func isValidEmail(candidate: String) -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}"
var valid = NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: candidate)
if valid {
valid = !candidate.contains("..")
}
return valid
}
这样使用
//Button Action
@IBAction func onClickRegrBtn(_ sender: UIButton) {
//Check net connection here
let networkReachability = Reachability.forInternetConnection()
let networkStatus:Int = (networkReachability?.currentReachabilityStatus())!.rawValue
if networkStatus == NotReachable.rawValue {
let msg = SharedClass.sharedInstance.noNetMsg
SharedClass.sharedInstance.alert(view: self, title: "", message: msg)//Display alert message
} else {
let mobileTrimmedString = mobileNoTF.text?.trimmingCharacters(in: .whitespaces) //Trim white spaces
if mobileTrimmedString != "" {
if isValidPhone(phone: mobileTrimmedString!) == false {
SharedClass.sharedInstance.alert(view: self, title: "", message: "Please enter valid mobile number")
} else {
UserDefaults.standard.set(mobileTrimmedString, forKey: "mobile") //setObject
sendMobileNumber()//Call function...
}
} else {
mobileNoTF.text = ""
//Call alert function
SharedClass.sharedInstance.alert(view: self, title: "", message: "Please enter mobile number")
}
}
}
Swift 4+
您可以使用简化的 regex "^[6-9]\d{9}$"
^ #Match the beginning of the string
[6-9] #Match a 6, 7, 8 or 9
\d #Match a digit (0-9 and anything else that is a "digit" in the regex engine)
{9} #Repeat the previous "\d" 9 times (9 digits)
$ #Match the end of the string
From Reference
印度 10 位数字手机验证(可以以 6,7,8,9 开头)-
extension String {
var isValidContact: Bool {
let phoneNumberRegex = "^[6-9]\d{9}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneNumberRegex)
let isValidPhone = phoneTest.evaluate(with: self)
return isValidPhone
}
}
用法:-
print("9292929292".isValidContact)//true
print("5454545454".isValidContact)//false
对于电子邮件验证,您可以检查 this
"validate Email"-Swift 4 的解决方案:
创建这个 class:
import Foundation
public class EmailAddressValidator {
public init() {
}
public func validateEmailAddress(_ email: String) -> Bool {
let emailTest = NSPredicate(format: "SELF MATCHES %@", String.emailValidationRegEx)
return emailTest.evaluate(with: email)
}
}
private extension String {
static let emailValidationRegEx = "(?:[\p{L}0-9!#$%\&'*+/=?\^_`{|}~-]+(?:\.[\p{L}0-9!#$%\&'*+/=?\^_`{|}" +
"~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\" +
"x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[\p{L}0-9](?:[a-" +
"z0-9-]*[\p{L}0-9])?\.)+[\p{L}0-9](?:[\p{L}0-9-]*[\p{L}0-9])?|\[(?:(?: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]?|[\p{L}0-9-]*[\p{L}0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21" +
"-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])"
}
并像这样使用它:
let validator = EmailAddressValidator()
let isValid = validator.validateEmailAddress("testmail@testmail.com")
Swift 4 & Swift 5:
func isValidPhone(phone: String) -> Bool {
let phoneRegex = "^[0-9+]{0,1}+[0-9]{5,16}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
return phoneTest.evaluate(with: phone)
}
func isValidEmail(email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,64}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: email)
}
- +1994423565 - 有效
- ++1994423565 - 无效
- 01994423565 - 有效
- 001994423565 - 有效
- something@example.com - 有效
- something@.com - 无效
iksnae 精彩回答的更新版本。它不是正则表达式,但我认为它是验证所有国家/地区的 phone 号码的最佳解决方案,因为它 足够聪明,可以知道该国家/地区的 phone 扩展代码是否有效 还有。
extension String {
public var validPhoneNumber: Bool {
let types: NSTextCheckingResult.CheckingType = [.phoneNumber]
guard let detector = try? NSDataDetector(types: types.rawValue) else { return false }
if let match = detector.matches(in: self, options: [], range: NSMakeRange(0, self.count)).first?.phoneNumber {
return match == self
} else {
return false
}
}
}
print("\("+96 (123) 456-0990".validPhoneNumber)") //returns false, smart enough to know if country phone code is valid as well
print("\("+994 (123) 456-0990".validPhoneNumber)") //returns true because +994 country code is an actual country phone code
print("\("(123) 456-0990".validPhoneNumber)") //returns true
print("\("123-456-0990".validPhoneNumber)") //returns true
print("\("1234560990".validPhoneNumber)") //returns true
我正在使用以下代码进行 phone 号码验证。但我收到以下错误。我无法继续进行。帮助我们推进它。
class PhoneNumberValidation: Validation {
let PHONE_REGEX = "^\d{3}-\d{3}-\d{4}$"
func validate(value: String) -> (Bool, ValidationErrorType) {
if let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX) {
if phoneTest.evaluateWithObject(value) {
return (true, .NoError)
}
return (false, .PhoneNumber)
}
return (false, .PhoneNumber)
}
}
错误:swift:15:28:条件绑定中的绑定值必须是可选类型
是的,您的错误在 XCode 6.1
下方发生此错误是因为 if
条件必须 Bool
return 类型,但在您的 if 条件 Return 类型中是 NSPredicate
以便你得到错误 swift: 条件绑定中的绑定值必须是可选类型 你可以按下面的方式解决。
var phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
if phoneTest.evaluateWithObject(value) {
return (true, .NoError)
}
return (false, .PhoneNumber)
}
Email-Validations 在 Swift.
func isValidEmail(testStr:String) -> Bool {
print("validate emilId: \(testStr)")
let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\t| )*\r\n)?(?:\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+(?:\.[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\[|\])|(?:\\(?:\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)(?:\.[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)*)|(?:\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\.){3}(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\])))(?:(?:(?:(?: )*(?:(?:(?:\t| )*\r\n)?(?:\t| )+))+(?: )*)|(?: )+)?$"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
let result = emailTest.evaluateWithObject(testStr)
return result
}
使用Email-validation:
if isValidEmail("kirit@gmail.com"){
print("Validate EmailID")
}
else{
print("invalide EmailID")
}
Phone-Number 在 Swift
中验证 func validate(value: String) -> Bool {
let PHONE_REGEX = "^\d{3}-\d{3}-\d{4}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluate(with: value)
return result
}
以下代码适用于 xcode 6.3 beta
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}"
let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch)
let result = range != nil ? true : false
return result
}
使用方法:
例如。
if isValidEmail(email.text) == false{
//your code here
}
Swift 3.0 到 5.0 更新的解决方案:
//MARK: - Validation Extension
extension String {
//To check text field or String is blank or not
var isBlank: Bool {
get {
let trimmed = trimmingCharacters(in: CharacterSet.whitespaces)
return trimmed.isEmpty
}
}
//Validate Email
var isEmail: Bool {
do {
let regex = try NSRegularExpression(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", options: .caseInsensitive)
return regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.count)) != nil
} catch {
return false
}
}
var isAlphanumeric: Bool {
return !isEmpty && range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil
}
//validate Password
var isValidPassword: Bool {
do {
let regex = try NSRegularExpression(pattern: "^[a-zA-Z_0-9\-_,;.:#+*?=!§$%&/()@]+$", options: .caseInsensitive)
if(regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil){
if(self.characters.count>=6 && self.count<=20){
return true
}else{
return false
}
}else{
return false
}
} catch {
return false
}
}
}
使用电子邮件验证:
if(txtEmail.isEmail) {
}
Swift 2.0 解
将这些行粘贴到代码中的任意位置。(或在您的 Constant 文件中)
extension String {
//To check text field or String is blank or not
var isBlank: Bool {
get {
let trimmed = stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
return trimmed.isEmpty
}
}
//Validate Email
var isEmail: Bool {
do {
let regex = try NSRegularExpression(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", options: .CaseInsensitive)
return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.count)) != nil
} catch {
return false
}
}
//validate PhoneNumber
var isPhoneNumber: Bool {
let charcter = NSCharacterSet(charactersInString: "+0123456789").invertedSet
var filtered:NSString!
let inputString:NSArray = self.componentsSeparatedByCharactersInSet(charcter)
filtered = inputString.componentsJoinedByString("")
return self == filtered
}
}
File-New-File。制作一个 Swift class 命名为 AppExtension.Add 如下。
extension UIViewController{
func validateEmailAndGetBoolValue(candidate: String) -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}"
return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluateWithObject(candidate)
}
}
Use:
var emailValidator:Bool?
self.emailValidator = self.validateEmailAndGetBoolValue(resetEmail!)
print("emailValidator : "+String(self.emailValidator?.boolValue))
Use a loop to alternate desired results.
OR
extension String
{
//Validate Email
var isEmail: Bool {
do {
let regex = try NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .CaseInsensitive)
return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
} catch {
return false
}
}
}
Use:
if(resetEmail!.isEmail)
{
AppController().requestResetPassword(resetEmail!)
self.view.makeToast(message: "Sending OTP")
}
else
{
self.view.makeToast(message: "Please enter a valid email")
}
另一个为了多样性的解决方案..
public extension String {
public var validPhoneNumber:Bool {
let types:NSTextCheckingType = [.PhoneNumber]
guard let detector = try? NSDataDetector(types: types.rawValue) else { return false }
if let match = detector.matchesInString(self, options: [], range: NSMakeRange(0, characters.count)).first?.phoneNumber {
return match == self
}else{
return false
}
}
}
//and use like so:
if "16465551212".validPhoneNumber {
print("valid phone number")
}
也许 Swift 中更好的 phone 验证器 2:
extension String {
var isPhoneNumber: Bool {
do {
let detector = try NSDataDetector(types: NSTextCheckingType.PhoneNumber.rawValue)
let matches = detector.matchesInString(self, options: [], range: NSMakeRange(0, self.characters.count))
if let res = matches.first {
return res.resultType == .PhoneNumber && res.range.location == 0 && res.range.length == self.characters.count
} else {
return false
}
} catch {
return false
}
}
}
Swift 3:
private func validate(phoneNumber: String) -> Bool {
let charcterSet = NSCharacterSet(charactersIn: "+0123456789").inverted
let inputString = phoneNumber.components(separatedBy: charcterSet)
let filtered = inputString.joined(separator: "")
return phoneNumber == filtered
}
Kirit Modi 关于 Swift 3 的电子邮件验证的回应:
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\t| )*\r\n)?(?:\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+(?:\.[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\[|\])|(?:\\(?:\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)(?:\.[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)*)|(?:\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\.){3}(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\])))(?:(?:(?:(?: )*(?:(?:(?:\t| )*\r\n)?(?:\t| )+))+(?: )*)|(?: )+)?$"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
let result = emailTest.evaluate(with: testStr)
return result
}
Phone 仅适用于 ّIran phone 数字
的正则表达式func isValidPhone(phone: String) -> Bool {
let PHONE_REGEX = "^09[0-9'@s]{9,9}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluate(with: phone)
return result
}
更新 Swift 3
extension String {
var isPhoneNumber: Bool {
do {
let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue)
let matches = detector.matches(in: self, options: [], range: NSMakeRange(0, self.characters.count))
if let res = matches.first {
return res.resultType == .phoneNumber && res.range.location == 0 && res.range.length == self.characters.count
} else {
return false
}
} catch {
return false
}
}
}
您可以创建单独的 class 进行验证,如下所示:
enum AIValidationRule: Int {
case
EmptyCheck,
MinMaxLength,
FixedLength,
EmailCheck,
UpperCase,
LowerCase,
SpecialCharacter,
DigitCheck,
WhiteSpaces,
None
}
let ValidationManager = AIValidationManager.sharedManager
func validateTextField(txtField:AITextField, forRule rule:AIValidationRule, withMinimumChar minChar:Int, andMaximumChar maxChar:Int) -> (isValid:Bool, errMessage:String, txtFieldWhichFailedValidation:AITextField)? {
switch rule {
case .EmptyCheck:
return (txtField.text?.characters.count == 0) ? (false,"Please enter \(txtField.placeholder!.lowercased())",txtField) : nil
case .MinMaxLength:
return (txtField.text!.characters.count < minChar || txtField.text!.characters.count > maxChar) ? (false,"\(txtField.placeholder!) should be of \(minChar) to \(maxChar) characters",txtField) : nil
case .FixedLength:
return (txtField.text!.characters.count != minChar) ? (false,"\(txtField.placeholder!) should be of \(minChar) characters",txtField) : nil
case .EmailCheck:
return (!(txtField.text?.isValidEmail())!) ? (false,"Please enter valid email",txtField) : nil
case .UpperCase:
return ((txtField.text! as NSString).rangeOfCharacter(from: NSCharacterSet.uppercaseLetters).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one uppercase letter",txtField) : nil
case .LowerCase:
return ((txtField.text! as NSString).rangeOfCharacter(from: NSCharacterSet.lowercaseLetters).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one lowercase letter",txtField) : nil
case .SpecialCharacter:
let symbolCharacterSet = NSMutableCharacterSet.symbol()
symbolCharacterSet.formUnion(with: NSCharacterSet.punctuationCharacters)
return ((txtField.text! as NSString).rangeOfCharacter(from: symbolCharacterSet as CharacterSet).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one special letter",txtField) : nil
case .DigitCheck:
return ((txtField.text! as NSString).rangeOfCharacter(from: NSCharacterSet(charactersIn: "0123456789") as CharacterSet).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one digit letter",txtField) : nil
case .WhiteSpaces:
return (txtField.text!.containsAdjacentSpaces() || txtField.text!.isLastCharcterAWhiteSpace()) ? (false,"\(txtField.placeholder!) seems to be invalid",txtField) : nil
case .None:
return nil
}
}
func validateTextField(txtField:AITextField, forRules rules:[AIValidationRule]) -> (isValid:Bool, errMessage:String, txtFieldWhichFailedValidation:AITextField)? {
return validateTextField(txtField: txtField, forRules: rules, withMinimumChar: 0, andMaximumChar: 0)
}
func validateTextField(txtField:AITextField, forRules rules:[AIValidationRule], withMinimumChar minChar:Int, andMaximumChar maxChar:Int) -> (isValid:Bool, errMessage:String, txtFieldWhichFailedValidation:AITextField)? {
var strMessage:String = ""
for eachRule in rules {
if let result = validateTextField(txtField: txtField, forRule: eachRule, withMinimumChar: minChar, andMaximumChar: maxChar) {
if(eachRule == AIValidationRule.EmptyCheck){
return result
}else{
strMessage += "\(strMessage.characters.count == 0 ? "" : "\n\n") \(result.errMessage)"
}
}
}
return strMessage.characters.count > 0 ? (false,strMessage,txtField) : nil
}
使用Swift 3
func validate(value: String) -> Bool {
let PHONE_REGEX = "^\d{3}-\d{3}-\d{4}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluate(with: value)
return result
}
Swift 3 验证电子邮件
class func validateEmail(email: String) -> Bool{
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}"
return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: email)
}
Phone 号码验证
class func validatePhoneNumber(value: String) -> Bool {
let PHONE_REGEX = "^\d{3}-\d{3}-\d{4}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluate(with: value)
return result
}
For Swift 3.0 and above
var isPhoneNumber: Bool{
let allowedCharacters = CharacterSet(charactersIn: "+0123456789").inverted
let inputString = components(separatedBy: allowedCharacters)
let filtered = inputString.joined(separator: "")
return self == filtered}
Updated for Swift :
使用以下代码验证电子邮件、姓名、手机和密码;
// Name validation
func isValidName(_ nameString: String) -> Bool {
var returnValue = true
let mobileRegEx = "[A-Za-z]{2}" // "^[A-Z0-9a-z.-_]{5}$"
do {
let regex = try NSRegularExpression(pattern: mobileRegEx)
let nsString = nameString as NSString
let results = regex.matches(in: nameString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
// password validation
func isValidPassword(_ PasswordString: String) -> Bool {
var returnValue = true
let mobileRegEx = "[A-Za-z0-9.-_@#$!%&*]{5,15}$" // "^[A-Z0-9a-z.-_]{5}$"
do {
let regex = try NSRegularExpression(pattern: mobileRegEx)
let nsString = PasswordString as NSString
let results = regex.matches(in: PasswordString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
// email validaton
func isValidEmailAddress(_ emailAddressString: String) -> Bool {
var returnValue = true
let emailRegEx = "[A-Z0-9a-z.-_]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,3}"
do {
let regex = try NSRegularExpression(pattern: emailRegEx)
let nsString = emailAddressString as NSString
let results = regex.matches(in: emailAddressString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
// mobile no. validation
func isValidPhoneNumber(_ phoneNumberString: String) -> Bool {
var returnValue = true
// let mobileRegEx = "^[789][0-9]{9,11}$"
let mobileRegEx = "^[0-9]{10}$"
do {
let regex = try NSRegularExpression(pattern: mobileRegEx)
let nsString = phoneNumberString as NSString
let results = regex.matches(in: phoneNumberString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
//如何使用?
let isFullNameValid = isValidName("ray")
if isFullNameValid{
print("Valid name...")
}else{
print("Invalid name...")
}
Swift 4.1.
func isValidPhone(phone: String) -> Bool {
let phoneRegex = "^[0-9]{6,14}$";
let valid = NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: phone)
return valid
}
func isValidEmail(candidate: String) -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"
var valid = NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: candidate)
if valid {
valid = !candidate.contains("..")
}
return valid
}
Swift 4.2 和 Xcode 10.1
//For mobile number validation
func isValidPhone(phone: String) -> Bool {
let phoneRegex = "^((0091)|(\+91)|0?)[6789]{1}\d{9}$";
let valid = NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: phone)
return valid
}
//For email validation
func isValidEmail(candidate: String) -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}"
var valid = NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: candidate)
if valid {
valid = !candidate.contains("..")
}
return valid
}
这样使用
//Button Action
@IBAction func onClickRegrBtn(_ sender: UIButton) {
//Check net connection here
let networkReachability = Reachability.forInternetConnection()
let networkStatus:Int = (networkReachability?.currentReachabilityStatus())!.rawValue
if networkStatus == NotReachable.rawValue {
let msg = SharedClass.sharedInstance.noNetMsg
SharedClass.sharedInstance.alert(view: self, title: "", message: msg)//Display alert message
} else {
let mobileTrimmedString = mobileNoTF.text?.trimmingCharacters(in: .whitespaces) //Trim white spaces
if mobileTrimmedString != "" {
if isValidPhone(phone: mobileTrimmedString!) == false {
SharedClass.sharedInstance.alert(view: self, title: "", message: "Please enter valid mobile number")
} else {
UserDefaults.standard.set(mobileTrimmedString, forKey: "mobile") //setObject
sendMobileNumber()//Call function...
}
} else {
mobileNoTF.text = ""
//Call alert function
SharedClass.sharedInstance.alert(view: self, title: "", message: "Please enter mobile number")
}
}
}
Swift 4+
您可以使用简化的 regex "^[6-9]\d{9}$"
^ #Match the beginning of the string
[6-9] #Match a 6, 7, 8 or 9
\d #Match a digit (0-9 and anything else that is a "digit" in the regex engine)
{9} #Repeat the previous "\d" 9 times (9 digits)
$ #Match the end of the string
From Reference
印度 10 位数字手机验证(可以以 6,7,8,9 开头)-
extension String {
var isValidContact: Bool {
let phoneNumberRegex = "^[6-9]\d{9}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneNumberRegex)
let isValidPhone = phoneTest.evaluate(with: self)
return isValidPhone
}
}
用法:-
print("9292929292".isValidContact)//true
print("5454545454".isValidContact)//false
对于电子邮件验证,您可以检查 this
"validate Email"-Swift 4 的解决方案: 创建这个 class:
import Foundation
public class EmailAddressValidator {
public init() {
}
public func validateEmailAddress(_ email: String) -> Bool {
let emailTest = NSPredicate(format: "SELF MATCHES %@", String.emailValidationRegEx)
return emailTest.evaluate(with: email)
}
}
private extension String {
static let emailValidationRegEx = "(?:[\p{L}0-9!#$%\&'*+/=?\^_`{|}~-]+(?:\.[\p{L}0-9!#$%\&'*+/=?\^_`{|}" +
"~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\" +
"x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[\p{L}0-9](?:[a-" +
"z0-9-]*[\p{L}0-9])?\.)+[\p{L}0-9](?:[\p{L}0-9-]*[\p{L}0-9])?|\[(?:(?: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]?|[\p{L}0-9-]*[\p{L}0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21" +
"-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])"
}
并像这样使用它:
let validator = EmailAddressValidator()
let isValid = validator.validateEmailAddress("testmail@testmail.com")
Swift 4 & Swift 5:
func isValidPhone(phone: String) -> Bool {
let phoneRegex = "^[0-9+]{0,1}+[0-9]{5,16}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
return phoneTest.evaluate(with: phone)
}
func isValidEmail(email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,64}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: email)
}
- +1994423565 - 有效
- ++1994423565 - 无效
- 01994423565 - 有效
- 001994423565 - 有效
- something@example.com - 有效
- something@.com - 无效
iksnae 精彩回答的更新版本。它不是正则表达式,但我认为它是验证所有国家/地区的 phone 号码的最佳解决方案,因为它 足够聪明,可以知道该国家/地区的 phone 扩展代码是否有效 还有。
extension String {
public var validPhoneNumber: Bool {
let types: NSTextCheckingResult.CheckingType = [.phoneNumber]
guard let detector = try? NSDataDetector(types: types.rawValue) else { return false }
if let match = detector.matches(in: self, options: [], range: NSMakeRange(0, self.count)).first?.phoneNumber {
return match == self
} else {
return false
}
}
}
print("\("+96 (123) 456-0990".validPhoneNumber)") //returns false, smart enough to know if country phone code is valid as well
print("\("+994 (123) 456-0990".validPhoneNumber)") //returns true because +994 country code is an actual country phone code
print("\("(123) 456-0990".validPhoneNumber)") //returns true
print("\("123-456-0990".validPhoneNumber)") //returns true
print("\("1234560990".validPhoneNumber)") //returns true