Validate Email Address Code Example in Swift

With this short Swift code example I would like to share with you a simplified version of email address validation code in Swift. The example is simplified because it does not check for all possible variations of email addresses in the world but you can improve it buy enhancing the regular expression used. Although, if used as is, it should cover 99% of all regular email address formats.

  • Create regular expression pattern to validate email address
  • Put code that validates email address into a separate function called isValidEmailAddress(emailAddressString: String)
  • Call isValidEmailAddress(emailAddressString: String) with valid and invalid email address for validation

Validate Email Address Code Example in Swift

  
  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
}

Function Call to Validate Email Address in Swift

  

// Check with Valid Email Address
 let validEmailAddressValidationResult = isValidEmailAddress(emailAddressString: "my.EmailAddress@gmail.com")
 print(emailAddressValidationResult)

// Check with invalid Email Address
 let inValidEmailAddressValidationResult = isValidEmailAddress(emailAddressString: "my.EmailAddress@gmail.c")
 print(inValidEmailAddressValidationResult)

Checkout more Swift code examples at Swift Code Examples page.


Learn iOS Development with these Video Courses

The Complete iOS 11 & Swift Developer Course - Build 20 Apps

Use Xcode 9 & Swift 4 to make real apps like Uber and Instagram, with CoreML & ARKit. Includes AWS Credit and much more. Preview this video course. icon

How to Make a Freaking iPhone App - iOS 11 and Swift 4

iPhone App Development from scratch. Learn how to make iOS apps using Xcode 9. The Basics Include Pokemon Go & Snapchat. Learn to build iOS Apps with Xcode 9 and Swift 4. How to Make a Freaking iPhone App - iOS 11 and Swift 4 icon

iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course

A Complete iOS 11 and Xcode 9 Course with Swift 4 & Objective-C. Preview this video course. iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course icon