Email Validation in Swift


In this Swift tutorial, we are going to see how to validate an email in the easiest possible way. Here we are going to check if the format of an email is valid or not with simple Swift programming.

Below are given only 3 lines of code that will be able to perform our task:

import Foundation

let regExMatchEmail = "[A-Z0-9a-z._%+-][email protected][A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"

let predicateEmail = NSPredicate(format:"SELF MATCHES %@", regExMatchEmail)

print(predicateEmail.evaluate(with: "[email protected]"))

In the above program, we have created a regular expression with the regExMatchEmail constant that holds the email format.

Next, we have created the NSPredicate and store it in the constant with the name predicateEmail. We pass the regExMatchEmail as the second parameter.

After that, we are providing the email as the argument to the evaluate() method.

It will return boolean true or false depending on the email format. If the email format is correct then it will return boolean true, otherwise, it will return false for invalid email format.

In our case, the email [email protected] is a valid email. So it will return true.

Create a Swift function for email validation

It is recommended to create a function for email validation. The main working process will be the same as we have done above, but the code will be inside the function.

Below is the given program where we are creating a function and in the end, you can see how we call the function:

import Foundation

func isEmailValidCheck(_ email: String) -> Bool {
    
    let regExMatchEmail = "[A-Z0-9a-z._%+-][email protected][A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"

    let predicateEmail = NSPredicate(format:"SELF MATCHES %@", regExMatchEmail)
    
    return predicateEmail.evaluate(with: email)
    
}

print( isEmailValidCheck("[email protected]") )
 

Output:

true

We can use the function just created above in the Swift program to validate our email. We only have to pass our email string to the function parameter and it will evaluate if the provided email address is in a valid format or not.