Email & Phone Validation in Swift

IosSwiftIphoneXcodeNsregularexpression

Ios Problem Overview


i am using the following code for phone number validation. But i am getting the following error. I cant able to proceed further. Help us to take it forward.

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)
    }
}

Error : swift:15:28: Bound value in a conditional binding must be of Optional type

Ios Solutions


Solution 1 - Ios

Yes your Error is below in XCode 6.1

Xcode error screenshot

This error is occurs because of if conditional have to Bool return type, but in Your if condition Return type is NSPredicate so that you got error swift: Bound value in a conditional binding must be of Optional type you can solve as below.

    var phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
         if phoneTest.evaluateWithObject(value) {
                  return (true, .NoError)
             }
                 return (false, .PhoneNumber)
            }

Email-Validations in 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
        } 

Use of Email-validation:

    if isValidEmail("[email protected]"){
            print("Validate EmailID")
        }
        else{
            print("invalide EmailID")
        }

Phone-Number Validation in 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
        }

Solution 2 - Ios

Swift 3.0 to 5.0 Updated Solution:

//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
        }
    }
}

use of Email Validation:

if(txtEmail.isEmail) {

}

Swift 2.0 Solution

Paste these line anywhere in code.(or in your Constant file)

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
        
    }
}

Solution 3 - Ios

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)
    }

Solution 4 - Ios

Maybe a better phone validator in Swift 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
        }
    }
}

Solution 5 - Ios

Swift 4+

You can use simplified 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

Indian 10 Digit Mobile validation(can start with 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
    }
} 

Usage:-

print("9292929292".isValidContact)//true
print("5454545454".isValidContact)//false

For email validation you can check this

Solution 6 - Ios

The following code works in 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

}

how to use it:

Ex.

if isValidEmail(email.text) == false{
//your code here
}

Solution 7 - Ios

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
}

Solution 8 - Ios

Swift 3 Validate Email

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 Number Validation

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
}

Solution 9 - Ios

Updated version of iksnae's awesome answer. It's not a regex, but I think it's the best solution to validate all countries' phone numbers as it is smart enough to know if the country's phone extension code is valid as well.

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

Solution 10 - Ios

Updated for 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
        }
    }
}

Solution 11 - Ios

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
  }

Solution 12 - Ios

Swift 4.2 and 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
}

Use like this

//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")
        }
    }
}

Solution 13 - Ios

Phone regex only for ّIran phone number

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
        
    }

Solution 14 - Ios

> 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}

Solution 15 - Ios

Kirit Modi's response about Email Validation for 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
  }

Solution 16 - Ios

File-New-File.Make a Swift class named AppExtension.Add the following.

        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")
        				}

Solution 17 - Ios

You can create separate class for validation as below:

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
}

Solution 18 - Ios

Using 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
}

Solution 19 - Ios

> Updated for Swift :

Used below code for Email, Name, Mobile and Password Validation;

// 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
}

//How to use?

let isFullNameValid = isValidName("ray")

if isFullNameValid{
    print("Valid name...")
}else{
    print("Invalid name...")
}

Solution 20 - Ios

"validate Email"-Solution for Swift 4: Create this 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])+)\\])"
}

and use it like this:

let validator = EmailAddressValidator()
let isValid = validator.validateEmailAddress("[email protected]")

Solution 21 - Ios

another solution for variety sake..

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")
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSaikumarView Question on Stackoverflow
Solution 1 - IosKirit ModiView Answer on Stackoverflow
Solution 2 - IosSourabh SharmaView Answer on Stackoverflow
Solution 3 - IosRajesh LoganathanView Answer on Stackoverflow
Solution 4 - IosEPage_EdView Answer on Stackoverflow
Solution 5 - IosJackView Answer on Stackoverflow
Solution 6 - IosRonaldoh1View Answer on Stackoverflow
Solution 7 - IoszumzumView Answer on Stackoverflow
Solution 8 - Iosshiju86.vView Answer on Stackoverflow
Solution 9 - IosSamuel FolledoView Answer on Stackoverflow
Solution 10 - Iosajay_nasaView Answer on Stackoverflow
Solution 11 - IosGurjinder SinghView Answer on Stackoverflow
Solution 12 - IosNareshView Answer on Stackoverflow
Solution 13 - IosMohammad RazipourView Answer on Stackoverflow
Solution 14 - IosHiren PanchalView Answer on Stackoverflow
Solution 15 - IosWilsonView Answer on Stackoverflow
Solution 16 - IosAlvin GeorgeView Answer on Stackoverflow
Solution 17 - IosDhaval H. NenaView Answer on Stackoverflow
Solution 18 - IosSaneeshView Answer on Stackoverflow
Solution 19 - IosKiran JadhavView Answer on Stackoverflow
Solution 20 - IosJochen HolzerView Answer on Stackoverflow
Solution 21 - IosiksnaeView Answer on Stackoverflow