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: "[email protected]")

// Check with invalid Email Address
 let inValidEmailAddressValidationResult = isValidEmailAddress(emailAddressString: "my.Email[email protected]")

Checkout more Swift code examples at Swift Code Examples page.