How to validate an email address in Swift
This tutorial will see how to validate an email address in Swift. This is possible by taking an email address as a string and checking it with the regular expression of valid emails. Regular expression allows us to run a complex search and replace operations on a large number of combinations.
Step 1: Import the foundation library which contains all the basic functions, classes, and data types of swift.
Step 2: Declare the isvalid named function to check whether an email is valid or not of a return type string and pass an email (string) as a parameter to the function.
Step 3: Declare the regular expression pattern for email format.
Step 4: Then create an NSRegularExpression instance and pass the previously defined pattern to the instance as a parameter.
Step 5: Then define the NSRange instance with the length as the length of the email string and location as starting index of the string.
Step 6: Finally call the matches function on the regex defined before. Pass the email string to search within and set the range equal to the range defined before.
Step 7: Now if the count of results s equal to zero then return the string as “invalid email” and “valid email” otherwise.
Step 8: call the isvalid function, pass the email string as a parameter, and print the result.
Code: Email validation in Swift
Here is the complete swift code for checking whether the email is valid.
import Foundation
func isValid(email: String) -> String
{
var returnValue = "Valid Email"
let emailRegEx = "[A-Z0-9a-z.-_]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,3}"
let regex = try! NSRegularExpression(pattern: emailRegEx)
let nsRange = NSRange(location: 0, length: email.length)
let results = regex.matches(in: email, range: nsRange)
if results.count == 0
{
returnValue = "Invalid Email"
}
return returnValue
}
let Result1 = isValid(email: "donjoe@gmail.com")
print(Result1)
let Result2 = isValid(email: "donjoe#email.c")
print(Result2)Output:
$swift main.swift Valid Email Invalid Email
Also, refer to Ways to compare two strings in Swift
Leave a Reply