I know you already accept an answer but this idea just cross my mind. You can use URLComponents
to split the email address into user
and host
and validate each component separately:
func validate(emailAddress: String) -> Bool {
guard let components = URLComponents(string: "mailto://" + emailAddress),
let host = components.host else
{
return false
}
return host.components(separatedBy: ".").count == 2
}
print(validate(emailAddress: "hello@gmail.com")) // true
print(validate(emailAddress: "hello@gmail.com.net")) // false
print(validate(emailAddress: "hello")) // false
Your requirement has a big flaw in it though: valid domains can have two dots, like someone@bbc.co.uk
. Getting a regex pattern to validate an email is hard. Gmail, for example, will direct all emails sent to jsmith+abc@gmail.com
to the same inbox as jsmith@gmail.com
. The best way is to perform some rudimentary check on the email address, then email the user and ask them to click a link to confirm the email.