Email & Phone Validation in Swift

121,557

Solution 1

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

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

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

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

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

Share:
121,557
Saikumar
Author by

Saikumar

With Over all 14 years of extensive experience in Product &amp; Technology in Web Application and Mobile Technology and currently I am working one of the product based company which was the product scaled it to 5 million users installed under last 5 years. Specialist in Mobile Technology iOS Application, CoreData, AutoLayout, Cocoa Pods, Objective-C/Swift Android Studio, Advanced Java, Framework APIs (GPS, Webserive, GCM, etc) AFNnetworking for iOS, RetroFit for Android Jsonparser for iOS, IALib/SKKIT for In-Apppurchase, SocketIo for Chat WebRTC technology deployed for Voice call Revenue Modules of Apple In-App Purchase deployed and implemented Creation and development of project architecture from scratch, which includes all components such as database, business logic, client-server communication and user, interface (UI) in Android and iOS. Open Search Server SphinxRT deployed and implemented MongoDB &amp; GridFs deployed and implemented Product Ideas and Innovations

Updated on July 08, 2022

Comments

  • Saikumar
    Saikumar almost 2 years

    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