create a regular expression that validates an email address in swift

Here is how you can create a regular expression to validate an email address in Swift:

main.swift
func validateEmail(email: String) -> Bool {
    let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
    return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: email)
}
201 chars
5 lines

In this function, we have defined a regular expression for a valid email address. This regular expression checks for the following:

  • The username of the email address can contain uppercase and lowercase letters, numbers, dots, underscores, percentage symbols, and plus and minus signs.
  • The domain name can contain uppercase and lowercase letters, numbers, dots, and hyphens.
  • The top-level domain can only be two or more letters.

We then use this regular expression to validate the email address passed into the validateEmail function. This function returns true if the email is valid, and false if it is not.

gistlibby LogSnag