How can I validate a string is an email address?

Asked on 2024-07-30

1 search

To validate a string as an email address, you can use regular expressions (regex) in Swift. Here's a simple example of how you can do this:

import Foundation

func isValidEmail(_ email: String) -> Bool {
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Z]{2,64}"
    let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
    return emailPred.evaluate(with: email)
}

// Example usage
let email = "example@domain.com"
print(isValidEmail(email))  // true or false

This function uses a regular expression to check if the input string matches the pattern of a typical email address. The NSPredicate class is used to evaluate the string against the regex pattern.

For more advanced error handling and validation techniques in Swift, you might find the sessions on Swift testing useful:

  1. Go further with Swift Testing
  2. Meet Swift Testing

These sessions cover various aspects of testing and validation in Swift, which can help you ensure your code handles errors gracefully and behaves as expected.