Email address Validation in Swift with example

This program checks how to validate the email address.

Dart provides a RegExp class for matching strings with regular expression

Following are the rules for a valid email address.

  • Email has different valid parts - sender name, @ symbol, and domain name
  • recipient and domain names may contain lower and upper case numbers
  • domain name contains an extension separated by a dot(.)
  • special characters are allowed in the sender’s name
  • sender name length is 64 characters
  • domain name is 256 characters

Swift Email validation example

The below example shows a isEmail method to a String extension, and it works in Swift 3 to 5 version.

  • Create a Regular expression pattern for email and pass it to NSRegularExpression. You can check email regex from online tools.
  • Check a given String is a valid email using firstMatch() method
  • extension function returns true for valid email, else returns false.
  • Finally, call the String function using string.isEmail syntax. Here is an example.
import Foundation
let str = "[email protected]"
if(str.isEmail) {
             print("\(str) is a valid e-mail")
} else {
    print("\(str) is not a valid e-mail")

}

extension String {
    //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
        }
    }
}

You can also write a utility function to check the given email validation logic.